Go读文件
GO读文本文件
设置文件位置为
const filePath string = "/home/hysg/code/go/fun/readfile/a"
- os.open函数
一次读10个字节,当文件读完,就退出程序
package main
import (
"fmt"
"io"
"os"
)
func main() {
var b = make([]byte, 10)
const filePath string = "/home/hysg/code/go/fun/readfile/a"
fd, err := os.Open(filePath)
if err != nil {
panic(err)
}
defer fd.Close()
for {
n, err := fd.Read(b)
if err == io.EOF {
os.Exit(1)
} else if err != nil {
panic(err)
} else {
fmt.Println(string(b[:n]))
}
}
}
- ioutil.ReadFile函数
package main
import (
"fmt"
"io/ioutil"
)
func main() {
const filePath string = "/home/hysg/code/go/fun/readfile/a"
c, err := ioutil.ReadFile(filePath)
if err != nil {
panic(err)
}
fmt.Printf("%s", c)
}
- 使用ioutil.ReadAll函数
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
const filePath string = "/home/hysg/code/go/fun/readfile/a"
fd, err:=os.Open(filePath)
if err!=nil{
fmt.Println(err)
}else {
bytes, err:=ioutil.ReadAll(fd)
fmt.Println(string(bytes), err)
defer fd.Close()
}
}