golang读取文件
作者:互联网
golang读文件
1、os.Open()
//File文件读操作 func ReadFile() string { file, err := os.Open("./test.txt") if err != nil { fmt.Printf("err:%v\n", err) } defer file.Close() var chunk []byte buf := make([]byte, 100) for { count, err := file.Read(buf) if err != nil && err != io.EOF { fmt.Println("read buf fail", err) return "" } if count == 0 { break } chunk = append(chunk, buf[:count]...) } return string(chunk) }
2、ioutil.ReadFile
func ReadFile2() { b, _ := ioutil.ReadFile("./test.txt") fmt.Printf("string(b): %v\n", string(b)) }
3、ioutil.ReadAll
func ReadFile3() { f, _ := os.Open("./test.txt") // File实现了Reader defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { fmt.Printf("err: %v\n", err) } fmt.Printf("string(b): %v\n", string(b)) }
标签:ioutil,文件,读取,err,fmt,golang,buf,chunk,string 来源: https://www.cnblogs.com/wushaoyu/p/16534041.html