/ 2019-04-17
更多内容可关注公众号:Go程序员开发
文件写入
文件写入常用函数和方法:
func Open(name string) (file *File, err error)
Open打开一个文件用于读取。如果操作成功,返回的文件对象的方法可用于读取数据;对应的文件描述符具有O_RDONLY模式。如果出错,错误底层类型是*PathError。
func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
OpenFile是一个更一般性的文件打开函数,大多数调用者都应用Open或Create代替本函数。它会使用指定的选项(如O_RDONLY等)、指定的模式(如0666等)打开指定名称的文件。如果操作成功,返回的文件对象可用于I/O。如果出错,错误底层类型是*PathError。
打开标记:
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_CREATE配合使用,文件必须不存在
O_SYNC int = syscall.O_SYNC // 打开文件用于同步I/O
O_TRUNC int = syscall.O_TRUNC // 如果可能,打开时清空文件
)
文件权限(unix权限位):只有在创建文件时才需要,不需要创建文件可以设置为 0。os库虽然提供常量,但是我一般直接写数字,如0664。
如果你需要设置多个打开标记和unix权限位,需要使用位操作符"|"
func (f *File) Write(b []byte) (n int, err error)
Write向文件中写入len(b)字节数据。它返回写入的字节数和可能遇到的任何错误。如果返回值n!=len(b),本方法会返回一个非nil的错误。
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
WriteAt在指定的位置(相对于文件开始位置)写入len(b)字节数据。它返回写入的字节数和可能遇到的任何错误。如果返回值n!=len(b),本方法会返回一个非nil的错误。
func (f *File) WriteString(s string) (ret int, err error)
WriteString类似Write,但接受一个字符串参数。
代码实现:
package main
import (
"fmt"
"os"
)
func main() {
file1, err := os.Open("./file1.txt")
if err != nil {
fmt.Printf("open file1.txt err : %v\n", err)
}
if file1 != nil {
defer func(file *os.File) { file.Close() }(file1)
}
file2, err := os.OpenFile("./file2.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("openfile file2 err : %v\n", err)
}
if file2 != nil {
defer func(file *os.File) { file.Close() }(file2)
}
b1 := []byte("hello world ! hi write test !\n")
off, err := file2.Write(b1)
if err != nil {
fmt.Printf("file2 write err : %v\n", err)
}
fmt.Printf("file2 write success , off is %v\n", off)
b2 := []byte("hello golang ! hi writeat test !\n")
off, err = file2.WriteAt(b2, int64(off))
if err != nil {
fmt.Printf("file2 writeat err : %v\n", err)
}
fmt.Printf("file2 writeat success , off is %v\n", off)
str := "this is write string test .\n"
off, err = file2.WriteString(str)
if err != nil {
fmt.Printf("file2 write string err : %v\n", err)
}
fmt.Printf("file2 write string success , off is %v\n", off)
}
运行结果:
file2 write success , off is 30
file2 writeat success , off is 33
file2 write string success , off is 28
cat file2.txt
hello world ! hi write test !
hello golang ! hi writeat test !
this is write string test .
(2)