读取文件案列
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
file, err := os.Open("/Users/leiwen/Documents/2022/wen.txt")
if err != nil {
fmt.Println("Open file err=", err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString(' ')
if err == io.EOF {
fmt.Print(string(str))
break
}
fmt.Print((str))
}
}
写文件案列
package main
import (
"bufio"
"fmt"
"os"
"syscall"
)
const (
O_RDONLY int = syscall.O_RDONLY
O_WRONLY int = syscall.O_WRONLY
O_RDWR int = syscall.O_RDWR
O_APPEND int = syscall.O_APPEND
O_CREATE int = syscall.O_CREAT
O_EXCL int = syscall.O_EXCL
O_SYNC int = syscall.O_SYNC
O_TRUNC int = syscall.O_TRUNC
)
func main() {
file, err := os.OpenFile("/Users/leiwen/Documents/2022/wen.txt", O_RDWR|O_CREATE|O_APPEND, 0666)
if err != nil {
fmt.Println("OpenFile file err=", err)
return
}
str := "wel"
defer file.Close()
writer := bufio.NewWriter(file)
writer.WriteString(str)
writer.Flush()
}
使用ioutil进行读写
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file := "/Users/leiwen/Documents/2022/wen.txt"
file2 := "/Users/leiwen/Documents/2022/wen2.txt"
content, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println("ReadFile file err=", err)
}
fmt.Println(string(content))
err2 := ioutil.WriteFile(file2, content, 0666)
if err2 != nil {
fmt.Println("写入错误:", err)
}
}
推荐文章
go中文文档
为什么要避免在 Go 中使用 ioutil.ReadAll?