Golang OpenFile O_APPEND does not respect Seek

When I open a file in this mode:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR|os.O_APPEND, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

io.CopyN does not respect the position in which I was looking. It seems to be just being added to the tail of the file. Instead, if I open the file as follows:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

It works as I expected. io.CopyN writes the file from the “start” point I was looking for. Not sure if this is a feature or bug?

+3
source share
1 answer

This is definitely a function ( http://man7.org/linux/man-pages/man2/open.2.html ), and it is controlled by the underlying OS, not the golang runtime.

O_APPEND
          The file is opened in append mode.  Before each write(2), the
          file offset is positioned at the end of the file, as if with
          lseek(2).  O_APPEND may lead to corrupted files on NFS
          filesystems if more than one process appends data to a file at
          once.  This is because NFS does not support appending to a
          file, so the client kernel has to simulate it, which can't be
          done without a race condition.
+10
source

All Articles