读写文件追加
/**
创建一个新文件 写入内容 "hello world"
func OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile is the generalized open call; most users will use Open or Create instead.
It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist,
and the O_CREATE flag is passed, it is created with mode perm (before umask).
If successful, methods on the returned File can be used for I/O. If there is an error,
it will be of type *PathError.
r > 4
w > 2
x > 1
const ( //flag
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write. 读写模式打开文件
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing. 写操作时将数据附加到文件尾部
O_CREATE int = syscall.O_CREAT // create a new file if none exists. 如果不存在将创建一个新文件
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.和O_CREATE 配合使用,文件必须不存在
O_SYNC int = syscall.O_SYNC // open for synchronous I/O. 打开文件用于同步I/O
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened. 如果可能,打开时清空文件
)
*/
// 打开一个存在文件,在原来的内容追加内容 "Perosn police SI 社保"*/
filepath3 := "C:/Users/Administrator/Desktop/abc.txt"
file3,err3:=os.OpenFile(filepath3,os.O_RDONLY|os.O_APPEND,0666)
if err3 !=nil{
fmt.Println("File3 Open error",err3)
return
}
defer file3.Close()
//先读取原来文件的内容,并显示在终端
reader3 := bufio.NewReader(file3)
for {
str,err:=reader3.ReadString('\n')
if err == io.EOF{ //如果读取到文件的末尾
break
}
// 显示到终端
fmt.Print(str)
}
str3 := "Perosn police SI 社保\n"
witer3 :=bufio.NewWriter(file3)
for i:=0;i<5 ;i++ {
witer3.WriteString(str3)
}
witer3.Flush()
}