Today continue to learn golang file operations (adhere to adhere to ~)
in routine work, write file operation too normal, we look at how to file golang write.
package main
import (
"bufio"
"fmt"
"os"
)
/*
需求:
1. 向一个文件写入 10行 hello world
2. 在一个已经存在的文件末尾追加 10行 I love golang
3. 从我电脑电源文件夹拷贝 /home/dog500/video/苍老师1.flv 到 /tmp/苍老师1-bak.flv
*/
func WriteFile(filePath, str, action string) {
var mode int
if action == "rw" {
mode = os.O_WRONLY | os.O_TRUNC
} else {
mode = os.O_WRONLY | os.O_APPEND
}
file, err := os.OpenFile(filePath, mode, 0644)
if err != nil {
fmt.Println("文件打开失败: ", err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
num := 10
for i := 0; i < num; i++ {
_, err := writer.WriteString(str + "\r\n")
if err != nil {
if action == "rw" {
fmt.Println("写入文件失败:", err)
} else {
fmt.Println("追加文件失败:", err)
}
return
}
}
writer.Flush()
if action == "rw" {
fmt.Println("写入文件完成")
} else {
fmt.Println("追加文件完成")
}
}
func copyFile(srcFile, dstFile string) {
src, err := os.Open(srcFile)
if err != nil {
fmt.Println("打开文件源文件失败: ", err)
return
}
defer src.Close()
dst, err := os.OpenFile(dstFile, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
fmt.Println("打开目标文件失败: ", err)
return
}
defer dst.Close()
_, err = io.Copy(dst, src)
if err != nil {
fmt.Println("拷贝文件失败: ", err)
return
}
fmt.Println("文件拷贝完成")
}
func main() {
filePath := "/tmp/myfile.txt"
// 需求1
str := "Hello world"
action := "rw" // 清空写
WriteFile(filePath, str, action)
// 需求2,就直接在上面的文件屁股后面追加吧,偷个懒~
str = "I love golang"
action = "ra" // 追加写
WriteFile(filePath, str, action)
// 需求3, 明天写
srcFile := "/home/dog500/video/苍老师1.flv"
dstFile := "/tmp/苍老师1-bak.flv"
copyFile(srcFile, destFile)
}