Fseek
Jump to navigation
Jump to search
Description
- Reposition stream position indicator
- Sets the position indicator associated with the stream to a new position.
- For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.
- For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.
- If the function is called with other values for these arguments, support depends on the particular system and library implementation (non-portable).
- The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
- On streams open for update (read+write), a call to fseek allows to switch between reading and writing.
Syntax
int fseek ( FILE * stream, long int offset, int origin );
Parameters
- stream
- Pointer to a FILE object that identifies the stream.
- offset
- Binary files: Number of bytes to offset from origin.
- Text files: Either zero, or a value returned by ftell.
- origin
- Position used as reference for the offset. It is specified by one of the following constants defined in <cstdio> exclusively to be used as arguments for this function:
Constant Reference position SEEK_SET Beginning of file SEEK_CUR Current position of the file pointer SEEK_END End of file. Note: Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).
Return Value
- If successful, the function returns zero.
- Otherwise, it returns non-zero value.
- If a read or write error occurs, the error indicator (ferror) is set.
Example
#include <stdio.h>
main()
{
char fname[21] ;
int n ;
long num ;
FILE * fstr ;
printf ("File to open? ") ;
scanf ("%20s", fname) ;
fstr = fopen (fname, "r") ;
while ( printf ("character to read (number)? "),
scanf ("%ld", &num), num )
{ fseek (fstr, sizeof(int)*(num-1), SEEK_SET) ;
fread (&n, sizeof(int), 1, fstr) ;
printf (" value: %d \n", n) ;
}
fclose (fstr) ;
}