File Handling
Introduction to C
Structure of a C Program
Variables and Data Types
Input and Output
Operators in C
Decision Making
If Statement
if...else Statement
Nested if Statement
Nested if...else Statement
Switch Statement
Loops
For Loop
While Loop
Do While Loop
Loop Comparison
Arrays
Strings
Functions
Function Types
Library Functions
User-Defined Functions
Recursion Function
Pointers
Structures
File Handling
Common Mistakes
Ideas
File Handling
File Handling in C
What is File Handling?
File Handling is the process of storing data permanently in a file (usually on a hard disk). In C, files are treated as a stream of bytes.
We use file handling when we want our program's output to stay saved even after the computer is turned off. The basic workflow follows these four steps:
- Open a file.
- Read from or Write to the file.
- Close the file to free memory.
Basic Syntax and File Pointer
To work with files, we use a special pointer of type FILE (defined in <stdio.h>).
FILE *fptr;
fptr = fopen("filename.txt", "mode");
// Common Modes:
"w" - Write (creates new or overwrites)
"r" - Read (opens existing)
"a" - Append (adds to the end)
fptr = fopen("filename.txt", "mode");
// Common Modes:
"w" - Write (creates new or overwrites)
"r" - Read (opens existing)
"a" - Append (adds to the end)
Syntax
FILE *pointer_name;
pointer_name = fopen("file_name", "mode");
pointer_name = fopen("file_name", "mode");
Syntax
// Writing
fprintf(file_pointer, "format_string", variables);
// Reading
fscanf(file_pointer, "format_string", &variables);
fprintf(file_pointer, "format_string", variables);
// Reading
fscanf(file_pointer, "format_string", &variables);
Syntax
fclose(file_pointer);
Practical Examples
Example 1: Writing to a File
FILE *fptr; fptr = fopen("test.txt", "w"); if (fptr == NULL) { printf("Error opening file!"); } else { fprintf(fptr, "Hello SkillEco Students!"); fclose(fptr); // Always close your files }
Example 2: Reading from a File
char text[100]; FILE *fptr = fopen("test.txt", "r"); if (fptr != NULL) { // Read the first word and print it fscanf(fptr, "%s", text); printf("Content: %s", text); fclose(fptr); }
Critical Concept: Always check if your file pointer is
NULL after using fopen. If the file doesn't exist or you don't have permission to access it, the pointer will be NULL, and trying to use it will crash your program.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on File Handling to test your knowledge.
Browse Quizzes »