首页 > 解决方案 > os.O_TRUNC 是做什么的?

问题描述

func OpenFile(name string, flag int, perm FileMode) (*File, error)

f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE|O_TRUNC, 0755)

“O_TRUNC”在写入之前是否清空整个文件?“截断”是什么意思?

此外,该函数是否ioutil.WriteFile()在写入之前清空整个文件?

标签: functiongomodulefuncwritefile

解决方案


os.O_TRUNC以前对“如果可能”使用措辞的定义存在一些混淆- 请参见此处

今天,文档阅读:

O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.

所以

“O_TRUNC”在写入之前是否清空整个文件?

是的。它本质上破坏了文件的内容 - 如果文件路径已经存在(并且是一个文件或指向现有文件的符号链接)。

同样来自ioutil.WriteFile 文档

... WriteFile 在写入之前将其截断。


推荐阅读