Name
fseek - Moves a file pointer.
Syntax
#include <stdio.h>
int fseek(stream, offset, origin)
FILE *stream;
long offset;
int origin;
Description
The fseek function moves the file pointer (if any)
associated with stream to a new location that is offset
bytes from origin. The next operation on the stream takes
place at the new location. On a stream open for update, the
next operation can be either a read or a write.
The argument origin must be one of the following constants
defined in stdio.h:
Origin Definition
SEEK_SET Beginning of file
SEEK_CUR Current position of file pointer
SEEK_END End-of-file
The fseek function can be used to reposition the pointer
anywhere in a file. The pointer can also be positioned
beyond the end of the file. However, an attempt to position
the pointer in front of the beginning of the file causes an
error.
The fseek function clears the end-of-file indicator and
negates the effect of any prior ungetc calls against stream.
When a file is opened for appending data, the current file
position is determined by the last I/O operation, not where
the next write would occur. If no I/O operation has yet
occurred on a file opened for appending, the file position
is the start of the file.
For streams opened in text mode, fseek has limited use
because carriage-return/line-feed (CR-LF) translations can
cause fseek to produce unexpected results.
The only fseek operations guaranteed to work on streams
opened in text mode are the following:
Seeking with an offset of zero relative to any of the
origin values.
Seeking from the beginning of the file with an offset
value returned from a call to ftell.
Return Value
If successful, fseek returns zero. Otherwise, it returns a
nonzero value. On devices incapable of seeking, the return
value is undefined.
See Also
ftell(DOS), lseek(DOS), rewind(S)
Example
#include <stdio.h>
FILE *stream; main() {
char line[81];
int result;
stream = fopen("data","w+");
fprintf(stream,"This is the first line in file
'data'.\n");
result = fseek(stream,0L,SEEK_SET); /* Position
pointer */
if (result)
perror("fseek failed");
else {
printf("File pointer is set to the beginning
of file.\n");
fgets(line,80,stream);
printf("%s",line);
} }
This program opens the file data and moves the pointer to
the file's beginning.
(printed 6/18/89)