Name
fseek
Synopsis
Moves the access position in a file
#include <stdio.h> intfseek
( FILE *fp
, longoffset
, intorigin
);
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 ...
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.