Fseek in C
Fseek in C
The fseek() function is used to move the cursor in the file to the desired position.
Syntax of fseek() function
Note: An offset into a file is simply the character location within that file.
1. fseek(fp, 0, SEEK_END);
Offset = 0, new file position is the beginning of the file
Position = SEEK_END, file pointer is moved to the end of the file.
2. “Welcome home”
fseek(fp,-4,2);
fprintf(fp,"removed");
offset = -4, new file position is “h” in “welcome home”
position = 2, means its SEEK_END, so the file pointer is moved to the end of the file at last.
OUTPUT: Welcome removed
3. “Welcome removed”
int n = 5;
fseek(fp,-8,2);
fprintf(fp,"%d",n);
offset = -8, new file position is “space” between Welcome and removed.
Pos = 2, means after manipulations in file, pointer moves to end of file
OUTPUT: Welcome5removed
NOTE: Negative values in offset means, the file pointer positions can be moved backwards also.
W e l c o m e h o m e
Bytes 0 1 2 3 4 5 6 7 8 9 10 11
-4 -3 -2 -1 From, fp = 0, offset = -4