change the read/write position of a file
#include <stdio.h> int fseek( FILE *fp, long int offset, int where );
The fseek() function changes the read/write position of the file specified by fp. This position defines the character that will be read or written on the next I/O operation on the file. The argument fp is a file pointer returned by fopen() or freopen(). The argument offset is the position to seek to, relative to one of three positions specified by the argument where. Allowable values for where are:
The fseek() function clears the end-of-file indicator, and undoes any effects of the ungetc() function on the same file.
The ftell() function can be used to obtain the current position in the file before changing it. The position can be restored by using the value returned by ftell() in a subsequent call to fseek() with the where parameter set to SEEK_SET.
The size of a file can be determined by the following example, which saves and restores the current position of the file:
#include <stdio.h> long int filesize( FILE *fp ) { long int save_pos, size_of_file; save_pos = ftell( fp ); fseek( fp, 0L, SEEK_END ); size_of_file = ftell( fp ); fseek( fp, save_pos, SEEK_SET ); return( size_of_file ); } void main() { FILE *fp; fp = fopen( "file", "r" ); if( fp != NULL ) { printf( "File size=%ld\n", filesize( fp ) ); fclose( fp ); } }
ANSI
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
errno, fgetpos(), fopen(), fsetpos(), ftell()