Nearby lessons

65 of 72

C - File Handling

File handling allows a C program to save information in a file and use it again later. In this lesson, you will learn why files are useful and the basic steps for working with files.

1. Why Do We Need Files?

Variables store data in memory while a program is running. When the program ends, that data is usually lost. Files help us save information so we can use it later.

Example: A student management program can save student names and marks in a file.

2. Basic Steps of File Handling

  1. Declare a file pointer.
  2. Open the file using fopen().
  3. Check whether the file opened successfully.
  4. Read from or write to the file.
  5. Close the file using fclose().
Example02
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("notes.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "Learning C file handling\n");
12 fclose(fp);
13 
14 printf("Data saved successfully\n");
15 return 0;
16}
Output
Data saved successfully

3. Common File Functions

  • fopen() opens a file.
  • fprintf() writes formatted data.
  • fputs() writes a string.
  • fgets() reads a line of text.
  • fclose() closes an opened file.
📝 Key Takeaways
  • Files can keep information after a program ends.
  • Include stdio.h to use basic file-handling functions.
  • Use FILE * to work with an opened file.
  • Check fopen for NULL and close opened files with fclose.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3