Search code examples
c++cboostfile-locking

Is tellp safe to use with file locking


The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this:

  1. open
  2. lock
  3. operate on file contents
  4. unlock
  5. close the file

However, I will be opening the file for append and want to call tellp to see where I am. Is this safe to do in the above scenario? Won't the file pointer be set as soon as the file is opened before the lock and thus potentially not protected? If so, is there a standard idiom to get around this?


Solution

  • This may be environment-specific, but on the majority of platforms:

    When a file is opened for append the file pointer is adjusted immediately before every write. So, if you use tellp before locking the file, it might not tell you where your newly appended bytes are going to go, but you shouldn't have two processes using locking somehow still appending the same range of bytes.