C File Pointers – ftell(), fseek(), and rewind()
In C, a file pointer of type FILE *
is used to manage file operations. It keeps track of the current position in the file and is used in almost all file functions like fopen()
, fclose()
, fgetc()
, and more.
๐ FILE * Pointer
When you open a file using fopen()
, it returns a pointer of type FILE *
which acts like a connection between your program and the file. All operations like read/write happen using this pointer.
๐งช Example: Basic FILE Pointer Usage
#include <stdio.h> int main() { FILE *fp = fopen("info.txt", "w"); if (fp == NULL) { printf("Error opening file.\n"); return 1; } fprintf(fp, "Learning C File Pointers!\n"); fclose(fp); printf("File written using FILE pointer.\n"); return 0; }
๐ ftell() – Get Current Position
The ftell()
function returns the current position of the file pointer in bytes from the beginning.
๐งช Example: Using ftell()
#include <stdio.h> int main() { FILE *fp = fopen("info.txt", "r"); if (fp == NULL) { printf("File not found.\n"); return 1; } fgetc(fp); // Read a character long pos = ftell(fp); printf("Current file position: %ld\n", pos); fclose(fp); return 0; }
๐ fseek() – Move File Pointer
fseek()
allows you to move the file pointer to a specific location in the file.
SEEK_SET
โ Beginning of the fileSEEK_CUR
โ Current positionSEEK_END
โ End of file
๐งช Example: Using fseek()
#include <stdio.h> int main() { FILE *fp = fopen("info.txt", "r"); if (fp == NULL) { printf("Cannot open file.\n"); return 1; } fseek(fp, 0, SEEK_END); // Move to end long size = ftell(fp); // Get size printf("Size of file: %ld bytes\n", size); fclose(fp); return 0; }
๐ rewind() – Reset File Pointer
rewind()
resets the file pointer to the beginning of the file.
๐งช Example: Using rewind()
#include <stdio.h> int main() { FILE *fp = fopen("info.txt", "r"); if (fp == NULL) { printf("Unable to read file.\n"); return 1; } fgetc(fp); // read a char rewind(fp); // go back to start char ch = fgetc(fp); printf("First character after rewind: %c\n", ch); fclose(fp); return 0; }
๐ง Quick Recap
FILE *
is your gateway to any file in C.ftell()
tells you where you are in the file.fseek()
lets you jump to any position.rewind()
resets everything back to the start!
๐ก Practice Tip
Create your own file, write some text, then try using fseek()
to jump to different positions and read from there!