I'm new to C and am using fseek. My question is, what exactly does it do?
eg: fseek(FILE *stream, -1, SEEK_CUR)
will read 1 character backwards, so is it already at the end of the file?
Does that mean fseek(FILE *stream, 0, SEEK_CUR)
does nothing?
And how do we apply the functions after fseek
to a data structure?
I'm new to C and am using
fseek
. My question is, what exactly does it do?
fseek
sets the file position indicator for the stream pointed to by stream
. The new position will be given by the offset in conjunction with the flag:
For SEEK_SET
, the offset is relative to the start of the file.
For SEEK_CUR
the offset is relative to the current indicator position.
For SEEK_END
it's relative to end-of-file.
eg:
fseek(FILE *stream, -1, SEEK_CUR)
will read 1 character backwards, so is it already at the end of the file?
It may be at beginning, in the middle or at the end, the current position is where it is right now. If the indicator is at the end of the file it will be moved one byte back.
It does not read characters, as stated, it positions the indicator to the desired position, by offset, from it's current position as explained above.
Does that mean
fseek(FILE *stream, 0, SEEK_CUR)
does nothing?
In practical terms it does nothing visible, because the offset is 0 it does not move the indicator, it just places it at the same position. It does clear the end-of-file status (resets the EOF
flag as mentioned by @rici).
From C11 N1570 §7.21.9.2
#include <stdio.h> int fseek(FILE *stream, long int offset, int whence);
Description:
2 The
fseek
function sets the file position indicator for the stream pointed to bystream
. If a read or write error occurs, the error indicator for the stream is set andfseek
fails.
3 For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified bywhence
. The specified position is the beginning of the file ifwhence
isSEEK_SET
, the current value of the file position indicator ifSEEK_CUR
, or end-of-file ifSEEK_END
. A binary stream need not meaningfully support fseek calls with awhence
value ofSEEK_END
.
4 For a text stream, eitheroffset
shall be zero, oroffset
shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file andwhence
shall beSEEK_SET
.
5 After determining the new position, a successful call to thefseek
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 successfulfseek
call, the next operation on an update stream may be either input or output.Returns:
6 The
fseek
function returns nonzero only for a request that cannot be satisfied.