当前位置:网站首页>Go language foundation ----- 13 ----- file
Go language foundation ----- 13 ----- file
2022-07-03 07:37:00 【Mango sauce】
1 Document classification and why documents are needed
1.1 Document classification and why documents are needed
1) Device file :
The screen ( Standard output equipment ) fmt.Println() Write content from standard output device .
keyboard ( Standard input devices ) fmt.Scan() Read content from standard input device .2) Disk files , A file placed on a storage device :
1、 text file Open... In Notepad , Can see the content ( It's not a mess ).
2、 Binary Open... In Notepad , Can see the content ( It's garbled ).3) Why do you need files ?
1、 Memory power loss , Program end , The contents of memory disappear .
2、 Put files on disk , Program end , The files still exist .
2 Document common operation interface introduction and use
1、 create a file
Law 1: Recommended use
func Create(name string) (file *File, err Error)
Create a new file based on the filename provided , Return a file object , Default permissions are 0666 The file of , The returned file object is readable and writable .
Law 2:
func NewFile(fd uintptr, name string) *File
Create the corresponding file according to the file descriptor , Return a file object
2、 Open file
Law 1:
func Open(name string) (file *File, err Error)
This method opens a name called name The file of , But it's read-only , The internal implementation actually calls OpenFile.
Law 2: Recommended use
func OpenFile(name string, flag int, perm uint32) (file *File, err Error)
Open name as name The file of ,flag It's the way it's opened , read-only 、 Reading and writing, etc ,perm It's authority
3、 Writing documents
Law 1:
func (file *File) Write(b []byte) (n int, err Error)
write in byte Type of information to file
Law 2:
func (file *File) WriteAt(b []byte, off int64) (n int, err Error)
Start writing... At the specified location byte Type information
Law 3:
func (file *File) WriteString(s string) (ret int, err Error)
write in string Information to file
4、 Reading documents
Law 1:
func (file *File) Read(b []byte) (n int, err Error)
Read data to b in
Law 2:
func (file *File) ReadAt(b []byte, off int64) (n int, err Error)
from off Start reading data to b in
5、 Delete file
func Remove(name string) Error
Call this function to delete the filename name The file of
3 Use of standard equipment documents
Here is just a brief note .
package main
import (
"fmt"
"os"
)
func main() {
//os.Stdout.Close() // After closing , Unable to output
//fmt.Println("are u ok?") // To the standard output device ( The screen ) Write content
// 1. standard output
// Standard equipment documentation (os.Stdout), The default is on , Users can use
//os.Stdout
os.Stdout.WriteString("are u ok?\n")
//os.Stdin.Close() // After closing , Unable to input
// 2. The standard input
var a int
fmt.Println(" Please enter a: ")
fmt.Scan(&a) // Read content from standard input device , Put it in a in
fmt.Println("a = ", a)
}
4 WriteString Use
package main
import (
"fmt"
"os"
)
func WriteFile(path string) {
// 1. New file
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// 2. After use , Need to close file
defer f.Close()
// 3. Write to the file
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func main() {
path := "./demo.txt"
WriteFile(path)
}
Generate a demo.txt:
5 Read Use
package main
import (
"fmt"
"io"
"os"
)
func WriteFile(path string) {
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// After use , Need to close file
defer f.Close()
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func ReadFile(path string) {
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
buf := make([]byte, 1024*2) //2k size
//n Represents the length of the content read from the file
n, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF {
// File error , At the same time, there is no end
fmt.Println("err1 = ", err1)
return
}
fmt.Println(string(buf[:n]))
}
func main() {
path := "./demo.txt"
// Write
//WriteFile(path)
// read
ReadFile(path)
}
Read the contents written above :
6 With the help of bufio Read content by line
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func WriteFile(path string) {
// Open file , New file
f, err := os.Create(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// After use , Need to close file
defer f.Close()
var buf string
for i := 0; i < 10; i++ {
//"i = 1\n", This string is stored in buf in
buf = fmt.Sprintf("i = %d\n", i)
//fmt.Println("buf = ", buf)
n, err := f.WriteString(buf)
if err != nil {
fmt.Println("err = ", err)
}
fmt.Println("n = ", n)
}
}
func ReadFile(path string) {
// Open file
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
buf := make([]byte, 1024*2) //2k size
//n Represents the length of the content read from the file
n, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF {
// File error , At the same time, there is no end
fmt.Println("err1 = ", err1)
return
}
fmt.Println("buf = ", string(buf[:n]))
}
// Read one line at a time
func ReadFileLine(path string) {
// Open file
f, err := os.Open(path)
if err != nil {
fmt.Println("err = ", err)
return
}
// Close file
defer f.Close()
// Create a new buffer , Put the content in the buffer first
r := bufio.NewReader(f)
for {
// encounter '\n' End read , But it will connect '\n' Itself will also read into . But not because there is \n And stop , This is very good .
buf, err := r.ReadBytes('\n')
if err != nil {
if err == io.EOF {
// The file is over
break
}
fmt.Println("err = ", err)
}
fmt.Printf("buf = #%s#\n", string(buf))
}
}
func main() {
path := "./demo.txt"
//WriteFile(path)
//ReadFile(path)
ReadFileLine(path)
}
take WriteString Read the contents of by line , But it will connect \n It will also read :
But not because there is \n And stop reading , For example, modify demo.txt:
You can see that you can also read \n.
7 Copy file cases
package main
import (
"fmt"
"io"
"os"
)
func main() {
list := os.Args // Get command line parameters
if len(list) != 3 {
fmt.Println("usage: xxx srcFile dstFile")
return
}
srcFileName := list[1]
drcFileName := list[2]
if srcFileName == drcFileName {
fmt.Println(" Source and destination file names cannot be the same ")
return
}
// Open source file in read-only mode
sF, err1 := os.Open(srcFileName)
if err1 != nil {
fmt.Println("err1 = ", err1)
return
}
// Create a new destination file
dF, err2 := os.Create(drcFileName)
if err2 != nil {
fmt.Println("err2 = ", err2)
return
}
// Operation completed , Need to close file
defer sF.Close()
defer dF.Close()
// Core processing , Read content from source file , Write to the destination file , Read as much as you write
buf := make([]byte, 4*1024) //4k Size temporary buffer
for {
n, err := sF.Read(buf) // Read content from source file
if err != nil {
if err == io.EOF{
// File read complete
break
}
fmt.Println("err = ", err)
}
// Write to the destination file , Read as much as you write
dF.Write(buf[:n])
}
}
First, generate the executable program :
# Enter the corresponding drive letter
d:
#cd Go to the corresponding directory
cd D:\xxx\xxx
#build Generate executable
go build test.go
# Finally, execute the copy command
test.exe demo.txt yyy.txt
yyy The content and content of demo.txt It's the same , picture 、 The copy of the video is no problem .
Be careful : Need to use cmd Go to build, Do not use bash, I tried. No , Can only cmd Go to build. Otherwise, the parameter loss will be reported when the copy command is executed .
边栏推荐
- Hello world of vertx
- Arduino Serial系列函数 有关print read 的总结
- Circuit, packet and message exchange
- Take you through the whole process and comprehensively understand the software accidents that belong to testing
- The babbage industrial policy forum
- How long is the fastest time you can develop data API? One minute is enough for me
- Leetcode 213: 打家劫舍 II
- 【LeetCode】2. Valid Parentheses·有效的括号
- Use of generics
- Vertx restful style web router
猜你喜欢

Summary of Arduino serial functions related to print read

Lucene hnsw merge optimization

Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
![[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211](/img/55/fea5fe315932b92993d21f861befbe.png)
[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211

Map interface and method

Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!

Lucene skip table

密西根大学张阳教授受聘中国上海交通大学客座教授(图)

Use of other streams

IO stream system and FileReader, filewriter
随机推荐
Lombok cooperates with @slf4j and logback to realize logging
【LeetCode】2. Valid Parentheses·有效的括号
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机
Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
Read config configuration file of vertx
The difference between typescript let and VaR
Mail sending of vertx
Introduction of buffer flow
Circuit, packet and message exchange
Hello world of vertx
項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
OSI knowledge sorting
Download address collection of various versions of devaexpress
Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
圖像識別與檢測--筆記
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
docket
Application of pigeon nest principle in Lucene minshouldmatchsumscorer