docs: file 文件写入

This commit is contained in:
Shikong 2021-10-04 16:35:20 +08:00
parent 91211ca6df
commit 0105def808

67
base/file/write/main.go Normal file
View File

@ -0,0 +1,67 @@
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// 文件写入
// 以指定模式打开文件
// os.OpenFile(文件名 name, 文件模式/标志位 flag, 文件权限 perm)
// flag 文件模式/标志位
// os.O_WRONLY 只写
// os.O_CREATE 创建
// os.O_RDONLY 只读
// os.O_RDWR 读写
// os.O_TRUNC 清空
// os.O_APPEND 追加
// perm 文件权限
// 文件权限 使用 8进制数 表示 类似 linux 下的文件权限
// 读 04
// 写 02
// 执行 01
func main() {
fileName := "./test.file"
// os.TempDir() 获取 系统 临时目录
absPath, _ := filepath.Abs(filepath.Join(os.TempDir(), fileName))
fmt.Println("打开文件", absPath)
f, err := os.OpenFile(absPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
fmt.Println("文件打开失败", err)
}
defer func() {
_ = f.Close()
}()
fmt.Println("=========================================================")
fmt.Println("ioutil 写入文件")
// go 1.16 开始 ioutil.WriteFile 与清空文件 后 直接使用 os.Write 后写入效果相同
_ = ioutil.WriteFile(absPath, []byte("5. ioutil 写入数据\n"), 0644)
fmt.Println("=========================================================")
fmt.Println("原始方法 写入文件")
_, _ = f.Write([]byte("1. 写入测试\n"))
_, _ = f.WriteString("2. 写入测试\n")
fmt.Println("=========================================================")
fmt.Println("bufio 写入文件")
writer := bufio.NewWriter(f)
// bufio 的 写入 是指 缓冲区
// 调用 Flush 的时候 才 真正 写入文件
_, _ = writer.Write([]byte("3. bufio 写入测试\n"))
_, _ = writer.WriteString("4. bufio 写入测试\n")
// 真正写入文件 将数据从缓冲区写入文件
_ = writer.Flush()
}