C Programming Tutorial
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at desired location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and SEEK_END.
Example:
#include <stdio.h> void main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is javatpoint", fp); fseek( fp, 7, SEEK_SET ); fputs("Rama", fp); fclose(fp); }
newfile.txt
This is Rama
EXAMPLE PROGRAM FOR FSEEK(), SEEK_SET(), SEEK_CUR(), SEEK_END() FUNCTIONS IN C:
#include <stdio.h> int main () { FILE *fp; char data[60]; fp = fopen ("test.c","w"); fputs("Fresh2refresh.com is a programming tutorial website", fp); fgets ( data, 60, fp ); printf(Before fseek - %s", data); // To set file pointet to 21th byte/character in the file fseek(fp, 21, SEEK_SET); fflush(data); fgets ( data, 60, fp ); printf("After SEEK_SET to 21 - %s", data); // To find backward 10 bytes from current position fseek(fp, -10, SEEK_CUR); fflush(data); fgets ( data, 60, fp ); printf("After SEEK_CUR to -10 - %s", data); // To find 7th byte before the end of file fseek(fp, -7, SEEK_END); fflush(data); fgets ( data, 60, fp ); printf("After SEEK_END to -7 - %s", data); // To set file pointer to the beginning of the file fseek(fp, 0, SEEK_SET); // We can use rewind(fp); also fclose(fp); return 0; }
OUTPUT:
Before fseek – Fresh2refresh.com is a programming tutorial website
After SEEK_SET to 21 – a programming tutorial website
After SEEK_CUR to -10 – sh.com is a programming tutorial website
After SEEK_END to -7 – website