[GO]文件的读写

时间:2022-06-22 10:17:40

首先写一个文件

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 := ; i <= ; i++ {
buf = fmt.Sprintf("i = %d\n", 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, *)//2k大小 //n代表从文件读取文件的长度
n, err1 := f.Read(buf)
if err1 != nil && err1 != io.EOF{ //表示文件出错,同时没有到结尾
fmt.Println("read file err = ", err1)
return
}
fmt.Println("buf = \n ", string(buf[:n]))
}
func main() {
path := "./demo.txt"
ReadFile(path)
}

执行的结果为

buf =
i =
i =
i =
i =
i =
i =
i =
i =
i =
i =
i =