File Operations in C

File Operations in C


Introduction

File handling in C allows us to store data permanently in files instead of temporary memory.

👉 Using file operations, we can:

  • Create files
  • Read data
  • Write data
  • Update data

What is a File?

A file is:
👉 A collection of data stored on a storage device


Why Use File Operations?

  • ✔ Store data permanently
  • ✔ Handle large data
  • ✔ Data reuse
  • ✔ Used in real-world applications

File Pointer

👉 A file pointer is used to access a file

FILE *fp;

Opening a File

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

File Modes Table

Mode Description
r Read
w Write
a Append
r+ Read & Write

Writing to a File

#include <stdio.h>

int main() {
FILE *fp;

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

fprintf(fp, "Hello File Handling");

fclose(fp);

return 0;
}

Output

👉 Creates file and writes data


Reading from a File

#include <stdio.h>

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

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

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

printf("%s", str);

fclose(fp);

return 0;
}

Output

Hello File Handling

Closing a File

fclose(fp);

👉 Always close file after use


File Functions Table

Function Purpose
fopen() Open file
fprintf() Write to file
fscanf() Read from file
fclose() Close file

Important Notes

  • Always check if file opened successfully
  • Close file after use
  • Use correct file mode

Common Mistakes

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

Pro Tips

  • ✔ Always check file pointer
  • ✔ Use proper file modes
  • ✔ Handle errors properly
  • ✔ Practice file programs

Conclusion

File operations allow storing and managing data permanently. They are essential for real-world applications.

Master file handling to build advanced programs.

👉 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