fseek


fseek

Moves the access position in a file

 #include <stdio.h> int fseek ( FILE *fp , long offset , int origin  ); 

The fseek( ) function moves the file position indicator for the file specified by the FILE pointer argument. The new position is offset bytes from the position selected by the value of the origin argument, which may indicate the beginning of the file, the previous position, or the end of the file. Table 17-2 lists the permitted values for origin.

Table 17-2. Values for fseek( )'s origin argument

Value of origin

Macro name

Offset is relative to

0

SEEK_SET

The beginning of the file

1

SEEK_CUR

The current position

2

SEEK_END

The end of the file


You can use a negative offset value to move the file access position backward, but the position indicator cannot be moved backward past the beginning of the file. However, it is possible to move the position indicator forward past the end of the file. If you then perform a write operation at the new position, the file's contents between its previous end and the new data are undefined.

The fseek( ) function returns 0 if successful, or -1 if an error occurs.

Example

 typedef struct {  long id;                   double value;                } record; FILE *fp; record cur_rec = (record) { 0, 0.0 }; int reclength_file = sizeof(record); long seek_id = 123L; if ((fp = fopen("records", "r")) == NULL)   perror( "Unable to open records file" ); else do {   if ( 1 > fread( &cur_rec.id, sizeof (long), 1, fp ))     fprintf( stderr, "Record with ID %ld not found\n", seek_id );   else      // Skip rest of record     if ( fseek( fp, reclength_file - sizeof(long), 1 )       perror( "fseek failed" ); } while ( cur_rec.id != seek_id ); 

See Also

fgetpos( ), fsetpos( ), ftell( ), rewind( )



C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net