File Handling in C Programming – Complete Beginner Guide with Examples

File Handling in C Programming – Complete Beginner Guide with Examples

File handling is an essential part of C programming when you want to store data permanently.

Instead of losing data when a program ends, file handling allows programs to read and write data into files.

In this article, you will learn file handling in C programming from scratch with clear explanations and beginner-friendly examples.

What Is File Handling in C?

File handling in C allows you to work with files stored on your system.

You can:

  • Create files
  • Read data from files
  • Write data to files
  • Append data to files

FILE Pointer in C

To work with files, C uses a FILE pointer.

FILE *fp;

Opening a File

The fopen() function is used to open a file.

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

File Modes in C

  • r – Read mode
  • w – Write mode
  • a – Append mode
  • r+ – Read and write

Writing to a File

You can write data using fprintf().

fprintf(fp, "Hello C Programming");

Reading from a File

Use fscanf() or fgets() to read data.

fgets(buffer, 100, fp);

Appending Data to a File

Append mode allows you to add new data without deleting existing content.

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

Closing a File

Always close a file after use to free resources.

fclose(fp);

Common File Handling Mistakes

  • Not checking if file opened successfully
  • Forgetting to close files
  • Using wrong file mode

Why File Handling Is Important?

  • Permanent data storage
  • Database handling
  • Log files

Interview Questions on File Handling

  • What is FILE pointer?
  • Difference between write and append mode?
  • Why should files be closed?

Final Conclusion

File handling allows C programs to store and retrieve data efficiently. Mastering this concept helps you build real-world applications and improves your programming skills.

Comments

Popular posts from this blog

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

Top Coding Mistakes Beginners Make (And How to Fix Them the Right Way)

Top 10 Free Coding Websites Every Beginner Should Use in 2026