fseek
Repositions a file pointer on a stream.
Defined in header <stdio.h>
Syntax
#include <stdio.h>
int fseek(FILE *stream, long offset,int whence);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ | ■ |
Remarks
fseek sets the file pointer associated with stream to a new position that is offset bytes from the file location given by whence. For text mode streams, offset should be 0 or a value returned by ftell.
whence must be one of the values 0, 1, or 2, which represent three symbolic constants (defined in stdio.h) as follows:
| whence | File location | |
| SEEK_SET | (0) | File beginning |
| SEEK_CUR | (1) | Current file pointer position |
| SEEK_END | (2) | End-of-file |
fseek discards any character pushed back using ungetc.
fseek is used with stream I/O; for file handle I/O, use lseek.
After fseek, the next operation on an update file can be either input or output.
Return value
fseek returns 0 if the pointer is successfully moved and a nonzero on failure.
Note: fseek can return a zero, indicating that the pointer has been moved successfully, when in fact it has not been. This is because DOS, which actually resets the pointer, does not verify the setting. fseek returns an error code only on an unopened file or device.
See also
Example
#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
fclose(stream);
return 0;
}
long filesize(FILE *stream) {
long curpos, length;
/* save the current location in the file */
curpos = ftell(stream);
/* seek to the end of the file */
fseek(stream, 0L, SEEK_END);
/* get the current offset into the file */
length = ftell(stream);
/* restore saved cursor position */
fseek(stream, curpos, SEEK_SET);
return length;
}
Differences from modern implementations
Draft from general knowledge; not yet confirmed against the Borland run-time code.
- Seeking past the end is not an error, and the manual says so: DOS moves the file pointer
without checking it, so
fseekreturns 0 for almost any offset. It fails only on a stream that isn’t open. Modern implementations return -1 witherrno = EINVALfor a negative resulting position. - Text-mode offsets: because of CR LF translation, only 0 or a value from
ftellis meaningful on a text-mode stream. ISO C says the same, but on POSIX systems every stream is effectively binary, so arbitrary offsets work there. offsetis a 32-bitlong, and there is nofseeko/off_tor 64-bit variant.
Modern references
Stable link: /3.1/stdio.h/fseek/
· short form /3.1/fseek/