9

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)

Does "O_TRUNC" empty the entire file before writing? What do they mean with "truncates"?

Also, does the function ioutil.WriteFile() empty the entire file before writing?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

11

There was some confusion on previous definitions of os.O_TRUNC using the verbiage "if possible" - see here.

Today the docs read:

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

So

Does "O_TRUNC" empty the entire file before writing ?

Yes. It essentially clobbers the file's contents - if the file path exists already (and is a file or symlink to an existing file).

Similarly from ioutil.WriteFile docs:

... WriteFile truncates it before writing.

David Jones
  • 4,766
  • 3
  • 32
  • 45
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
  • 2
    For ordinary files the file is truncated on opening, which is before writing. And may, in the general case, be arbitrarily long before writing. You can truncate a file by opening it with O_TRUNC and closing it without writing anything. – David Jones Jun 06 '20 at 18:54