File Handling in C

📘 C 👁 28 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

File handling in C is used to store data permanently on secondary storage (files).
C provides file handling functions through the stdio.h library.


Types of Files

  1. Text Files

  2. Binary Files


File Pointer

  • A file is accessed using a FILE pointer

FILE *fp;

Opening a File

fopen() Function

fp = fopen("filename", "mode");

File Opening Modes

ModeDescription
rRead
wWrite
aAppend
r+Read and write
w+Write and read
a+Append and read

Closing a File

fclose(fp);

Writing to a File

Using fprintf()

fprintf(fp, "Hello C");

Using fputc()

fputc('A', fp);

Reading from a File

Using fscanf()

fscanf(fp, "%s", str);

Using fgetc()

ch = fgetc(fp);

Example Program (Write to File)

#include int main() { FILE *fp; fp = fopen("data.txt", "w"); if (fp == NULL) { printf("File cannot be opened"); return 0; } fprintf(fp, "Welcome to C"); fclose(fp); return 0; }

Example Program (Read from File)

#include int main() { FILE *fp; char ch; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("File not found"); return 0; } while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); } fclose(fp); return 0; }

feof() Function

Checks end of file.

feof(fp);

Advantages of File Handling

  • Permanent data storage

  • Data sharing between programs

  • Large data handling


Summary

  • File handling uses FILE pointer

  • fopen() opens a file

  • fclose() closes a file

  • Read and write using file functions

  • Supports text and binary files


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes