stdioinsists on the user inserting a buffer-flushing operation between each element of a read-write-read cycle.) To control this, the Random Access functions allow control over the implied read/write position in the file. The file position indicator is moved without the need for a read or a write, and indicates the byte to be the subject of the next operation on the file.
Three types of function exist which allow the file position indicator to be examined or changed. Their declarations and descriptions follow.
/* return file position indicator */
long ftell(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
/* set file position indicator to zero */
void rewind(FILE *stream);
/* set file position indicator */
int fseek(FILE *stream, long offset, int ptrname);
int fsetpos(FILE *stream, const fpos_t *pos);
Ftellreturns the current value (measured in characters) of the file position indicator if
streamrefers to a binary file. For a text file, a ‘magic’ number is returned, which may only be used on a subsequent call to
fseekto reposition to the current file position indicator. On failure,
-1Lis returned and
Rewindsets the current file position indicator to the start of the file indicated by
stream. The file's error indicator is reset by a call of
rewind. No value is returned.
Fseekallows the file position indicator for stream to be set to an arbitrary value (for binary files), or for text files, only to a position obtained from ftell, as follows:
- In the general case, the file position indicator is set to offset bytes (characters) from a point in the file determined by the value of
Offsetmay be negative. The values of
SEEK_SET, which sets the file position indicator relative to the beginning of the file,
SEEK_CUR, which sets the file position indicator relative to its current value, and
SEEK_END, which sets the file position indicator relative to the end of the file. The latter is not necessarily guaranteed to work properly on binary streams.
- For text files,
offsetmust either be zero or a value returned from a previous call to
ftellfor the same stream, and the value of
Fseekclears the end of file indicator for the given stream and erases the memory of any
ungetc. It works for both input and output.
- Zero is returned for success, non-zero for a forbidden request.
fseekit must be possible to encode the value of the file position indicator into a
long. This may not work for very long files, so the Standard introduces
fsetposwhich have been specified in a way that removes the problem.
Fgetposstores the current file position indicator for stream in the object pointed to by pos. The value stored is ‘magic’ and only used to return to the specified position for the same stream using fsetpos.
Fsetposworks as described above, also clearing the stream's end-of-file indicator and forgetting the effects of any ungetc operations.
For both functions, on success, zero is returned; on failure, non-zero is returned and errno is set.