Standard Library Functions in C

adplus-dvertising
fseek() Function
Previous Home Next

Description

The C library function, The fseek() function sets the file position indicator associated with stream according to the values of offset and origin. Its purpose is to support random-access I/O operations. The offset is the number of bytes from origin to seek to. The values for origin must be one of these macros (defined in ).

Declaration

Following is the declaration for fseek() function.

int fseek(FILE *stream, long int offset, int origin);

Parameters

stream - The stream whose file position indicator is to be modified.

offset - Number of bytes from origin.

Origin - This is the position from where offset is added. Initial position

Constant Description
SEEK_SETBeginning of file
SEEK_CURCurrent position of the file pointer
SEEK_ENDEnd of file

Return Value

If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined.

Example

#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");
exit(1);
}
if(fseek(fp, atol(argv[2]), SEEK_SET)) {
printf("Seek error.\n");
exit(1);
}
printf("Byte at %ld is %c.\n", atol(argv[2]), getc(fp));
fclose(fp);
return 0;
}

Output

Usage: SEEK filename byte
Previous Home Next