Six ways to write files in go language
The code of writefile.go is as follows:
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
s := []byte("Data to write\n")
f1, err := os.Create("f1.txt")
if err != nil {
fmt.Println("Cannot create file", err)
return
}
defer f1.Close()
fmt.Fprintf(f1, string(s))
f2, err := os.Create("f2.txt")
if err != nil {
fmt.Println("Cannot create file", err)
return
}
defer f2.Close()
n, err := f2.WriteString(string(s))
fmt.Printf("wrote %d bytes\n", n)
f3, err := os.Create("f3.txt")
if err != nil {
fmt.Println(err)
return
}
w := bufio.NewWriter(f3)
n, err = w.WriteString(string(s))
fmt.Printf("wrote %d bytes\n", n)
w.Flush()
f3.Close()
f4 := "f4.txt"
err = ioutil.WriteFile(f4, s, 0644)
if err != nil {
fmt.Println(err)
return
}
f5, err := os.Create("f5.txt")
if err != nil {
fmt.Println(err)
return
}
n, err = io.WriteString(f5, string(s))
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("wrote %d bytes\n", n)
f6, err := os.Create("f6.txt")
if err != nil {
fmt.Println("Cannot create file", err)
return
}
defer f6.Close()
n, err = f6.Write(s)
fmt.Printf("wrote %d bytes\n", n)
}
compile file
go build writefile.go
implement
./writefile
Where f2.WriteString
is to convert the string to byte data, and then call the same method as f6.Write(s)
.
ioutil.WriteFile(f4, s, 0644)
is to open the file first, and then call the same method as f6.Write(s)
write to file
f5 calls the method of the Writer interface, and decides which implementation to use according to the called structure. Of course, the above code uses the implementation of the File structure. So f2, f5, f6 actually call the same method in the above code.
f3 is *Writer with cache, which is the implementation of Writer structure.