Go operates text files
Go
When operating text files, like other languages, there are operations such as creating new files, opening files, writing files, reading files, deleting files, etc. Let’s take a look first.Go
Api for manipulating text files.
1. Create a new file
//Return the memory address of the File, error message; call through the os libraryfunc Create(name string) (file *File, err Error)
//Return the memory address of the file, call it through the os libraryfunc NewFile(fd int, name string) *File
2. Open the file
//Return the memory address of the File, error message; call through the os libraryfunc Open(name string) (file *File, err Error)
//Return the memory address of the File, error message, called through the os libraryfunc OpenFile(name string, flag int, perm unit32) (file *File, err Error)
3. Write to the file
//Write a slice, return the number of written ones, error message, and call through the memory address of Filefunc (file *File).Write(b []byte) (n int, err Error)
// Start writing from a certain position in the slice, return the number of written words, error message, and call through the memory address of Filefunc (file *File).WriteAt(b []byte, off int64) (n int, err Error)
//Write a string, return the number of written ones, error message, call through the memory address of Filefunc (file *File).WriteString(s string) (ret int, err Error)
4. Read the file
//Read a slice, return the number of reads, error message, call through the memory address of Filefunc (file *File).Read(b []byte) (n int, err Error)
//Read from a certain position in the slice, return the number of reads, error message, call through the memory address of the Filefunc (file *File).ReadAt(b []byte, off int64) (n int, err Error)
4. Delete the file
//Path the file into the path to delete the file, return the number of errorsfunc Remove(name string) Error
5. Close the file
func (f *File) Close() error
Example of usage
package main import ( "fmt" "os" ) func main() { fileName := "/home/wohu/gocode/src/" writeFile(fileName) readFile(fileName) } func writeFile(fileName string) { file, err := (fileName) if err != nil { (err) return } for i := 0; i <= 5; i++ { outStr := ("%s:%d\n", "hello, world", i) (outStr) ([]byte("abcd\n")) } () } func readFile(fileName string) { file, err := (fileName) if err != nil { (err) return } defer () buf := make([]byte, 1024) for { n, _ := (buf) if n == 0 { //0 means that EOF is reached break } (buf) } }
Output result:
wohu@wohu:~/gocode/src$ ls
wohu@wohu:~/gocode/src$ cat
hello, world:0
abcd
hello, world:1
abcd
hello, world:2
abcd
hello, world:3
abcd
hello, world:4
abcd
hello, world:5
abcd
wohu@wohu:~/gocode/src$
The above is the detailed content of the Go file operation (new open write, read, delete, close) study notes. For more information about Go file operation, please pay attention to my other related articles!