Search code examples
linuxfileglibc

how file offset of read() or write() change when file is truncated to zero by other people


Is file offset automatic changed to 0, or kept unchanged.

If the file offset is keep unchanged, what happen when read() or write() after truncate().


Solution

  • how file offset of read() or write() change when file is truncated

    The file offset of opened file descriptors remains unchanged[1].

    what happen when read() or write() after truncate().

    read():

    • Will read valid data if the offset is in range of the file.
    • Will read bytes equal to 0 if the offset is after the length of file but in the range of truncate[1].
    • Will return 0 (ie. no bytes read) if the offset is past the end of file[3].

    write():

    • Will write data to the file at the offset specified[4].
    • If the write is past the end-of-file, the file will be resized with padding zeros[2].

    [1] From posix truncate:

    If the file previously was larger than length, the extra data is discarded. If the file was previously shorter than length, its size is increased, and the extended area appears as if it were zero-filled.

    The truncate() function shall not modify the file offset for any open file descriptions associated with the file.

    [2] From posix lseek:

    The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

    [3] From posix read:

    No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned.

    [4] And from posix write:

    After a write() to a regular file has successfully returned:

    • Any successful read() from each byte position: in the file that was modified by that write shall return the data specified by the write() for that position until such byte positions are again modified.