C File Handling

What is File Handling?

File handling allows programs to read from and write to files on disk.

This is useful for saving data, logs, and configurations.

File Pointer

A file is handled using a FILE pointer.

Loading...
Output:

Opening a File

Use fopen() to open a file.

It returns a pointer to the file.

Loading...
Output:

File Modes

Common file modes include:

  • "r" – read
  • "w" – write (overwrite)
  • "a" – append

Closing a File

Always close files after use to free resources.

Loading...
Output:

Writing to a File

Use fprintf() to write formatted data to a file.

Loading...
Output:

Reading from a File

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

Loading...
Output:

Reading Character by Character

You can read one character at a time using fgetc().

Loading...
Output:

Checking File Errors

Always check if the file opened successfully.

Loading...
Output:

Appending to a File

Use append mode to add data without overwriting existing content.

Loading...
Output:

Real-World Example

Writing and reading from a file in one program.

Loading...
Output:

Why File Handling is Important

File handling is used in many real-world applications.

  • Saving data
  • Reading configuration files
  • Logging program output

Common Mistakes

Be careful with these:

  • Forgetting to close files
  • Not checking NULL pointer
  • Using wrong file mode

Practice

Write a program that writes text to a file and then reads and prints it.

Loading...
Output:

Need Help?