đ§ĩ Use of File Pointers in C
In C, a file pointer is a pointer to a FILE
object that represents a file stream. It is used to read, write, and manage files efficiently.
đš Declaring a File Pointer
FILE *fp;
đš Opening and Closing a File
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(fp, "Hello, File Pointer!\n");
fclose(fp);
return 0;
}
đš Common File Pointer Functions
Function | Purpose |
---|---|
fopen() | Open a file and get file pointer |
fclose() | Close the file |
fprintf() | Write formatted output to file |
fscanf() | Read formatted input from file |
fseek() | Move file pointer position |
ftell() | Get current position of file pointer |
rewind() | Reset file pointer to beginning |
đš Example: Using fseek() and ftell()
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Cannot open file.\n");
return 1;
}
fseek(fp, 5, SEEK_SET); // Move pointer 5 bytes from beginning
printf("Current position: %ld\n", ftell(fp));
fclose(fp);
return 0;
}
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ