File pointers in C are special pointers used to handle files. Every time you work with a file in C, you use a file pointer of type FILE * to manage it.
FILE, which holds information about a file being used (like current position, read/write mode, etc.).
FILE *fp;
Here, fp is a file pointer that can be used with functions like fopen(), fclose(), fread(), etc.
fp = fopen("data.txt", "r");
This opens the file data.txt in read mode. The pointer fp now points to the file's memory structure.
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Open for writing
if (fp == NULL) {
printf("File cannot be opened.\n");
return 1;
}
fprintf(fp, "File pointer example."); // Write to file
fclose(fp); // Close the file
return 0;
}
FILE *fp creates the file pointer.fopen() opens the file and returns a file pointer.fprintf() writes to the file using the pointer.fclose() closes the file.
The file pointer also keeps track of the current read/write position in the file. Functions like fseek(), ftell(), and rewind() can manipulate this position.
fseek(fp, offset, origin) — Moves the file pointer.ftell(fp) — Returns the current position.rewind(fp) — Resets the pointer to the beginning of the file.fseek() and ftell()
#include <stdio.h>
int main() {
FILE *fp = fopen("seek_example.txt", "w+");
fputs("Hello File!", fp);
fseek(fp, 0, SEEK_END); // Move to end
printf("Position: %ld", ftell(fp)); // Print position
rewind(fp); // Move back to beginning
char str[20];
fgets(str, 20, fp);
printf("\\nContent: %s", str);
fclose(fp);
return 0;
}
fseek() jumps to the end of the file.ftell() tells us the position.rewind() takes us back to the beginning.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!