Reading & Writing Files in C

Reading & Writing Files in C


Introduction

In C programming, reading and writing files allow us to store and retrieve data permanently.

👉 This is important for real-world applications like databases, logs, and reports.


File Pointer

FILE *fp;

👉 Used to access file


Opening a File

fp = fopen("file.txt", "mode");

Writing to a File

👉 Using fprintf()

#include <stdio.h>

int main() {
FILE *fp;

fp = fopen("data.txt", "w");

fprintf(fp, "Welcome to Dharani Tech Edu Hub");

fclose(fp);

return 0;
}

Output

👉 Creates file and writes data


Reading from a File

👉 Using fgets()

#include <stdio.h>

int main() {
FILE *fp;
char str[100];

fp = fopen("data.txt", "r");

fgets(str, sizeof(str), fp);

printf("%s", str);

fclose(fp);

return 0;
}

Output

Welcome to Dharani Tech Edu Hub

Writing Multiple Lines

#include <stdio.h>

int main() {
FILE *fp;

fp = fopen("multi.txt", "w");

fprintf(fp, "Line 1\n");
fprintf(fp, "Line 2\n");

fclose(fp);

return 0;
}

Reading Character by Character

#include <stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen("data.txt", "r");

while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}

fclose(fp);

return 0;
}

Output

👉 Displays file content character by character


File Functions Table

Function Purpose
fprintf() Write formatted data
fgets() Read line
fgetc() Read character
fputc() Write character

Important Notes

  • Always close file after use
  • Use correct mode (r, w, a)
  • Check if file opened successfully

Common Mistakes

  • ❌ Forgetting fclose()
  • ❌ File not found error
  • ❌ Wrong file mode
  • ❌ Not checking NULL pointer

Pro Tips

  • ✔ Use fgets() for safe reading
  • ✔ Use loops for reading files
  • ✔ Handle file errors
  • ✔ Practice file programs

Conclusion

Reading and writing files is essential for handling data permanently in C. It helps in building real-world applications.

Master file handling to improve your programming skills.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C