C Tutorial



FILE POINTERS IN C


📌 File Pointers in C

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.

🧠 What is a File Pointer?
A file pointer is a pointer to a structure of type FILE, which holds information about a file being used (like current position, read/write mode, etc.).

🔹 Declaring a File Pointer

FILE *fp;
  

Here, fp is a file pointer that can be used with functions like fopen(), fclose(), fread(), etc.

🔹 Opening a File with a File Pointer

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.

✨ Full Example Using File Pointer

#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;
}
  
Explanation:
- 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.

🔹 File Pointer as File Position Indicator

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.

✨ Example Using 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;
}
  
Explanation:
- fseek() jumps to the end of the file.
- ftell() tells us the position.
- rewind() takes us back to the beginning.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review