🔴 Advanced  ·  Lesson 36

File Handling in C

File Handling

File Handling

File handling allows a C program to store data permanently in files and read it later. C uses FILE pointer and functions from stdio.h.

FunctionUse
fopen()Open file
fclose()Close file
fprintf()Write formatted data
fscanf()Read formatted data
fgets()Read a line
fputs()Write a string

File Modes

ModeMeaning
rOpen existing file for reading
wCreate/overwrite file for writing
aAppend data at end
r+Read and write existing file
w+Read and write, overwrite/create
a+Read and append

Write File

C Language
#include <stdio.h>

int main() {
    FILE *fp = fopen("students.txt", "w");
    if(fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    fprintf(fp, "Roll Name Marks\n");
    fprintf(fp, "101 Aman 89\n");
    fprintf(fp, "102 Riya 94\n");

    fclose(fp);
    printf("Data written successfully");
    return 0;
}

Read File

C Language
#include <stdio.h>

int main() {
    FILE *fp = fopen("students.txt", "r");
    char line[100];

    if(fp == NULL) {
        printf("File not found");
        return 1;
    }

    while(fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }

    fclose(fp);
    return 0;
}

Summary

  • Use FILE * for file operations
  • Always check if fopen() returns NULL
  • Close every opened file using fclose()
  • Use correct mode: read, write or append
  • Use text functions for simple text files

File Handling

File handling से C program data को permanently files में store और later read कर सकता है। इसके लिए stdio.h के functions use होते हैं।

File Modes

ModeMeaning
rRead existing file
wWrite/overwrite
aAppend
r+Read + write
w+Read + write, overwrite

File Write

C Language
FILE *fp = fopen("data.txt", "w");
if(fp == NULL) {
    printf("File error");
    return 1;
}
fprintf(fp, "Hello File");
fclose(fp);

File Read

C Language
FILE *fp = fopen("data.txt", "r");
char line[100];
while(fgets(line, sizeof(line), fp) != NULL) {
    printf("%s", line);
}
fclose(fp);

सारांश

  • File handling permanent data storage देती है
  • FILE * pointer use होता है
  • fopen() के बाद NULL check करें
  • काम पूरा होने पर fclose() करें
  • Mode सही choose करें
← Back to C Tutorial