首先写一个文件
package main import ( "os" "fmt" ) func WriteFile(path string) { //打开文件,创建文件 f, err := os.Create(path) if err != nil { fmt.Println("err = ", err) return } //写文件 var buf string for i := 0; i <= 10; i++ { buf = fmt.Sprintf("i = %d ", i) _, err := f.WriteString(buf) if err != nil { fmt.Println("write file error = ", err) return } //fmt.Println(" n = ", n) } //关闭文件 defer f.Close() } func main() { path := "./demo.txt" WriteFile(path) }
执行完成后就会在程序的同目录生成一个demo.txt的文件,下面是文件的读
package main import ( "os" "fmt"
"io"
) func ReadFile(path string) { //打开文件 f, err := os.Open(path) if err != nil { fmt.Println("open file erro = " ,err) return } //关闭文件 defer f.Close() buf := make([]byte, 1024*2)//2k大小 //n代表从文件读取文件的长度 n, err1 := f.Read(buf) if err1 != nil && err1 != io.EOF{ //表示文件出错,同时没有到结尾 fmt.Println("read file err = ", err1) return } fmt.Println("buf = ", string(buf[:n])) } func main() { path := "./demo.txt" ReadFile(path) }
执行的结果为
buf = i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 i = 10