Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdio.h>
int fsetpos(FILE *stream, const fpos_t *pos);
#define _OPEN_SYS_UNLOCKED_EXT 1
#include <stdio.h>
int fsetpos_unlocked(FILE *stream, const fpos_t *pos);
The fsetpos() function moves the file position associated with stream to a new location within the file according to the value of the object pointed to by pos. The value of pos must be obtained by a call to the fgetpos() function. If successful, the fsetpos() function clears the EOF indicator, and cancels the effect of any previous ungetc() or ungetwc() function on the same stream.
If the call to the fsetpos() function is not valid, the call is treated as a flush, and the ungetc characters are discarded.
The fsetpos() function handles the double-byte character set (DBCS) state information for wide-oriented files. An fsetpos() function call to a position that no longer exists results in an error.
For text streams, the DBCS shift state is recalculated from the start of the record, which has a performance implication. The fsetpos() function repositions to the start of a multibyte character.
For binary streams, the DBCS shift state is set to the state saved by the fsetpos() function. If the record has been updated in the meantime, the shift state might be incorrect.
After the fsetpos() function call, the next operation on a stream in update mode can be an input or output operation.
Multivolume data sets performance: Using the fgetpos() and fsetpos() functions generally results in better repositioning performance compared to the ftell() and fseek() functions when working with multivolume data sets.
Large file support for MVS data sets, VSAM data sets, and z/OS UNIX files: The fsetpos() function implicitly supports operating on large files. Defining the _LARGE_FILES feature test macro is not required to use this function on large files.
If successful in changing the current position of the file, the fsetpos() function returns 0.
If unsuccessful, the fsetpos() function returns nonzero and sets errno.
/* This example opens a file called myfile.dat for reading.
After performing input operations (not shown), it moves the file
pointer to the beginning of the file and rereads the first byte.
*/
#include <stdio.h>
int main(void)
{
FILE *stream;
int retcode;
fpos_t pos, pos1, pos2, pos3;
char ptr[20]; /* existing file 'myfile.dat' has 20 byte records */
/* Open file, get position of file pointer, and read first record */
stream = fopen("myfile.dat", "rb");
fgetpos(stream,&pos);
pos1 = pos;
if (!fread(ptr,sizeof(ptr),1,stream))
printf("fread error\n");
/* Perform a number of read operations. The value of 'pos'
changes if 'pos' is passed to fgetpos() */
⋮
/* Re-set pointer to start of file and re-read first record */
fsetpos(stream,&pos1);
if (!fread(ptr,sizeof(ptr),1,stream))
printf("fread error\n");
fclose(stream);
}