fseek() function
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 catchmecoder", fp); fseek( fp, 7, SEEK_SET ); fputs("Pramesh gupta", fp); fclose(fp); } myfile.txt This is Pramesh gupta
rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times. Syntax:
void rewind(FILE *stream)
Example:
File: file.txt
this is a general text
rewind.c
#include <stdio.h> void main() { FILE *fp; char c; fp=fopen("file.txt","r"); while((c=fgetc(fp))!=EOF){ printf("%c",c); } rewind(fp); //moves the file pointer at beginning of the file while((c=fgetc(fp))!=EOF){ printf("%c",c); } fclose(fp); } Output: Hello catchmecoder... Hello catchmecoder...
ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell() function to get the total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file pointer at the end of file Syntax:
long int ftell(FILE *stream)
File: ftell.c
Example:
#include <stdio.h> void main () { FILE *fp; int length; fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("Size of file: %d bytes", length); } Output: Size of file: 23 bytes