fseek( ) and Random-Access I/O. McGraw-Hill The Complete Reference Fourth Edition
Annons
Annons
C h a p t e r 9 : F i l e I / O
229
fseek( ) and Random-Access I/O
You can perform random-access read and write operations using the C I/O system with the help of fseek( ), which sets the file position indicator. Its prototype is shown here: int fseek(FILE *fp, long int numbytes, int origin);
Here, fp is a file pointer returned by a call to fopen( ). numbytes is the number of bytes from origin that will become the new current position, and origin is one of the following macros:
Origin
Beginning of file
Current position
End of file
Macro Name
SEEK_SET
SEEK_CUR
SEEK_END
Therefore, to seek numbytes from the start of the file, origin should be SEEK_SET. To seek from the current position, use SEEK_CUR; and to seek from the end of the file, use SEEK_END. The fseek( ) function returns 0 when successful and a nonzero value if an error occurs.
The following program illustrates fseek( ). It seeks to and displays the specified byte in the specified file. Specify the filename and then the byte to seek to on the command line.
#include <stdio.h>
#include <stdlib.h> int main(int argc, char *argv[])
{
FILE *fp; if(argc!=3) { printf("Usage: SEEK filename byte\n"); exit(1);
} if((fp = fopen(argv[1], "rb"))==NULL) { printf("Cannot open file.\n");
Ladda ner
Annons