user1456632
user1456632

Reputation: 698

what are the side-effects of fseek(fp, 0, SEEK_CUR)

Presumably, this line should have no effect; seeking 0 bytes from the current location. However, I found the line in some legacy code, and without the line, nothing seems to work - even in python, with the equivalent fp.seek(0, os.SEEK_CUR)

Is it simply a buffer thing, or something deeper?

Upvotes: 3

Views: 1017

Answers (1)

The C standard says that you must seek when changing between reads and writes to the same file handle. C11 7.21.5.3p7:

  1. When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. [...]

All the side effects for fseek in the C standard revision C11 7.21.9.2p5:

  1. After determining the new position, a successful call to the fseek function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new position. After a successful fseek call, the next operation on an update stream may be either input or output.

Not all of this applies to Python 3, as Python 3 actually bypasses C stdio wherever possible; nor does Python even expose ungetc. Python 2 files were a thinner wrapper around stdio streams.

Upvotes: 4

Related Questions