go打开文件
go打开文件模式
O_RDONLY // open the file read-only.
O_WRONLY // open the file write-only.
O_RDWR // open the file read-write.
// The remaining values may be or'ed in to control behavior.
O_APPEND // append data to the file when writing.
O_CREATE // create a new file if none exists.
O_EXCL // used with O_CREATE, file must not exist.
O_SYNC // open for synchronous I/O.
O_TRUNC // truncate regular writable file when opened.
1.读全部
import (
"errors"
"fmt"
"io/ioutil"
)
f,err:=ioutil.ReadFile("./log.text") // ReadFile 用的 OpenFile(name, O_RDONLY, 0)
// filename 不存在就就报错
if err!=nil{
fmt.Println("出错啦")
}
err1 := errors.New("错误")
fmt.Println("出错啦",err1)
fmt.Println(string(f))
2.每次读多少字节
f,err:=os.Open("./log.text") // OpenFile(name, O_RDONLY, 0) 不存在就报错
if err !=nil{
fmt.Println("出错啦",err)
}
b:=make([]byte,3)
for {
_, err1 := f.Read(b)
if err1 == io.EOF {
fmt.Println(string(b))
break
} else if err1 != nil {
fmt.Println("粗错啦")
break
} else {
fmt.Println(string(b))
}
}
3.按行读
f,err:=os.Open("./log.text")
if err !=nil{
fmt.Println("出错啦",err)
}
s:=bufio.NewScanner(f)
for s.Scan(){
fmt.Println(s.Text())
}
4.创建(存在就清空)
fileobj, _ := os.Create("./creat.test") //OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
writeString, _ := fileobj.WriteString("哈哈哈\n")
fmt.Println(writeString)
5.append追加
f,_:=os.OpenFile("./log.text",os.O_CREATE|os.O_APPEND|os.O_RDWR,0666)
for i:=0;i<10;i++{
f.WriteString(fmt.Sprintf("哈哈哈%d\n",i))
}
永远不要高估自己