Move the file position indicator.
#include <stdio.h> int fseek(FILE *stream, long offset, int whence);
stream
A pointer to a file stream.
offset
The number of characters to move.
whence
The starting position to move from.
The fseek() function moves the file position indicator to allow random access to a file.
The function moves the file position indicator either absolutely or relatively. The whence argument can be one of three values defined in stdio.h:
The fseek() function undoes the last ungetc() call and clears the end-of-file status of stream.
The function has limited use when used with MS-DOS text files opened in text mode because of carriage return/line feed translations. The seek operations may be incorrect near the end of the file due to end-of-file translations.
The only operations guaranteed to work in MS-DOS text files opened in text mode are:
This facility may not be available on configurations of the EWL that run on platforms without file systems.
fseek() returns zero if it is successful and returns a nonzero value if it fails.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *f;
long int pos1, pos2, newpos;
char filename[80], buf[80];
// get a filename from the user
printf("Enter a filename to read.\n");
gets(filename);
// open a file for input
if (( f = fopen(filename, "r")) == NULL) {
printf("Can't open %s.\n", filename);
exit(1);
}
printf("Reading last half of first line.\n");
// get the file position indicator before and after
// reading the first line
pos1 = ftell(f);
fgets(buf, 80, f);
pos2 = ftell(f);
printf("Whole line: %s\n", buf);
// calculate the middle of the line
newpos = (pos2 - pos1) / 2;
fseek(f, newpos, SEEK_SET);
fgets(buf, 80, f);
printf("Last half: %s\n", buf);
fclose(f);
return 0;
}
Output:
Enter a filename to read.
itwerks
Reading last half of first line.
Whole line: The quick brown fox
Last half: brown fox