đŸ”ĸ File Handling in C

đŸ§ĩ Complete Tutorial: File Functions in C

In C programming, file handling lets you save data permanently to a file, retrieve it later, and manage real-world data efficiently. You’ll use special functions like fopen(), fclose(), fprintf(), and fscanf().

🔹 1. FILE Pointer

Declare a file pointer using:

FILE *fp;

🔹 2. fopen() – Open File

fp = fopen("data.txt", "w");
if (fp == NULL) {
    printf("Error opening file.\n");
    return 1;
}

Modes:

  • "r" - Read
  • "w" - Write (overwrite)
  • "a" - Append
  • "r+", "w+", "a+" - Read + Write modes

🔹 3. fprintf() – Write to File

fprintf(fp, "Name: %s, Age: %d\n", name, age);

🔹 4. fscanf() – Read from File

fscanf(fp, "%s %d", name, &age);

🔹 5. fclose() – Close File

fclose(fp);

Important to close files to release resources.

✅ Full Example: Student File Program

#include <stdio.h>

int main() {
    FILE *fp;
    char name[50];
    int age;

    fp = fopen("students.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file.\n");
        return 1;
    }

    fprintf(fp, "Alice 20\nBob 25\nCharlie 22\n");
    fclose(fp);

    fp = fopen("students.txt", "r");
    if (fp == NULL) {
        printf("Cannot open file.\n");
        return 1;
    }

    printf("Reading from file:\n");
    while (fscanf(fp, "%s %d", name, &age) != EOF) {
        printf("Name: %s, Age: %d\n", name, age);
    }

    fclose(fp);
    return 0;
}

🔚 Summary Table

FunctionPurpose
fopen()Open file in read/write mode
fprintf()Write to file with format
fscanf()Read from file with format
fclose()Close the file properly
C file functions tutorial, fopen fprintf fscanf fclose explained, how to read and write file in C, file pointer in C language, beginner C file handling guide

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ