golang 写文件--详细解释

1,不覆盖指定的文件

先看代码怎么写,下面再具体解释.

func writeToFile(msg string)  {
	f, err := os.OpenFile("/home/mingbai/del/koala.log", os.O_WRONLY&os.O_CREATE, 0666)
	if err != nil {
		log.Println(err.Error())
	}

	_, err = f.Write([]byte(msg))
	if err != nil {
		log.Println(err.Error())
	}
	f.Close()
}

OpenFile 这个函数不那么好理解,解释一下. 第一个参数 就是文件路径.

第二个参数是一个 文件打开方式的flag是读是写 还是读写;是追加还是清空等, 第一种类型同第二种类型可用'|' (与或非的或)操作连接,表示两个都要. 其实你还可以加三个,比如:os.O_WRONLY|os.O_CREATE|os.O_APPEND 表示写模式打开,没有则创建且追加的方式写入.

第三个参数是操作文件的权限, 就是Linux 文件权限的那种4 读,2 写, 1 执行; 可累加.比较常见,不多解释了.

flag 有下面这些参数可选:

// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
	// 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_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
)

英文版不想看? 没事儿, 我这还有中文版!


    O_RDONLY 以只读文式打开文件。
    O_WRONLY 以只写方式打开文件。
    O_RDWR 以读写方式打开文件
    O_APPEND 以追加方式打开文件,写入的数据将追加到文件尾。
    O_CREATE 当文件不存在时创建文件。
    O_EXCL 与 O_CREATE 一起使用,当文件已经存在时 Open 操作失败。
    O_SYNC 以同步方式打开文件。每次 write 系统调用后都等待实际的物理 I/O 完成后才返回,默认(不使用该标记)是使用缓冲的,也就是说每次的写操作是写到系统内核缓冲区中,等系统缓冲区满后才写到实际存储设备。
    O_TRUNC 如果文件已存在,打开时将会清空文件内容。必须于 O_WRONLY 或 O_RDWR 配合使用。截断文件,需要有写的权限。

2, ioutil 会覆盖文件的内容

ioutil 也能很方便的读写文件,但是类似下面这样写会覆盖文件的内容,有时候不符合需求.

func writeToFile2(msg string)  {
	if err := ioutil.WriteFile("/home/mingbai/del/koala.log", []byte("hello"), 777); err != nil{
		os.Exit(111)
		log.Println(err.Error())
	}
}

有用的话点个赞哦~

posted @ 2019-08-30 18:25  名白  阅读(2651)  评论(0编辑  收藏  举报