fsetpos() — Set File Position
Format
#include <stdio.h>
int fsetpos(FILE *stream, const fpos_t *pos);
Language Level
ANSI
Threadsafe
Yes
Description
The fsetpos()
function
moves any file position that is associated with stream to
a new location within the file according to the value pointed to by pos.
The value of pos was obtained by a previous
call to the fgetpos()
library
function.
If successful, fsetpos()
clears
the end-of-file indicator, and undoes the effect of any previous ungetc()
function
on the same stream.
After the fsetpos()
call,
the next operation on a stream in update mode can be input or output.
Return Value
If fsetpos()
successfully
changes the current position of the file, it returns 0. A
nonzero return value indicates an error.
The value of errno can be set to:
- Value
- Meaning
- EBADF
- The file pointer or descriptor is invalid.
- EBADPOS
- The position that is specified is not valid.
- EINVAL
- The value specified for the argument is not correct. You might
receive this errno when you compile your program with *IFSIO, and
you are working with a file in the QSYS file system. For example,
"/qsys.lib/qtemp.lib/myfile.file/mymem.mbr"
. - ENODEV
- Operation was attempted on a wrong device.
- ENOPOS
- No record at the specified position.
- ERECIO
- The file is open for record I/O.
- ESTDERR
stderr
cannot be opened.- ESTDIN
stdin
cannot be opened.- ESTDOUT
stdout
cannot be opened.- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
The
fsetpos()
function
cannot be used for files that are opened with type=record.
Also, the fsetpos()
function
can only support setting the position to the beginning of the file
if: - your program is compiled with *IFSIO, and
- you are working on a file in the QSYS file system.
Example
This example opens a file mylib/myfile for
reading. After performing input operations,
fsetpos()
moves
the file pointer to the beginning of the file and rereads the first
byte. #include <stdio.h>
FILE *stream;
int main(void)
{
int retcode;
fpos_t pos;
char ptr[20]; /* existing file 'mylib/myfile' has 20 byte records */
int i;
/* Open file, get position of file pointer, and read first record */
stream = fopen("mylib/myfile", "rb");
fgetpos(stream,&pos);
if (!fread(ptr,sizeof(ptr),1,stream))
perror("fread error");
else printf("1st record: %s\n", ptr);
/* Perform another read operation on the second record */
/* - the value of 'pos' changes */
if (!fread(ptr,sizeof(ptr),1,stream))
perror("fread error");
else printf("2nd record: %s\n", ptr);
/* Re-set pointer to start of file and re-read first record */
fsetpos(stream,&pos);
if (!fread(ptr,sizeof(ptr),1,stream))
perror("fread error");
else printf("1st record again: %s\n", ptr);
fclose(stream);
}