File Handling in C Programming (fopen, fprintf, fscanf, fclose)
About this page
This is a practical quick-start for file handling with fopen, fprintf, fscanf and fclose. Use it when you want working code fast.
For full coverage of file modes, binary files, and advanced operations, see File Management. For a complete runnable program, see File Input Output Example Program.
Introduction
C treats files as streams. The <stdio.h> library provides fopen, fprintf, fscanf, fgets, fputc and fclose for text file operations.
Opening and Closing Files
FILE *fp = fopen("data.txt", "w"); /* write (create/truncate) */
FILE *fp = fopen("data.txt", "r"); /* read */
FILE *fp = fopen("data.txt", "a"); /* append */
if (fp == NULL) {
perror("fopen failed");
return 1;
}
fclose(fp);Write to a File
#include <stdio.h>
int main(void) {
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fprintf(fp, "Hello, File!\n");
fprintf(fp, "Number: %d\n", 42);
fclose(fp);
printf("Data written to output.txt\n");
return 0;
}Read from a File
#include <stdio.h>
int main(void) {
FILE *fp = fopen("output.txt", "r");
char line[256];
if (fp == NULL) {
perror("Error opening file");
return 1;
}
while (fgets(line, sizeof(line), fp) != NULL)
printf("%s", line);
fclose(fp);
return 0;
}Sample Output (after running write then read)
Hello, File!
Number: 42File Open Modes
| Mode | Meaning |
|---|---|
"r" | Read — file must exist |
"w" | Write — creates or truncates |
"a" | Append — creates if missing |
"r+" | Read and write |
"rb" / "wb" | Binary read/write |
Best Practices
Common Mistakes
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- Memory management In C — Concept — static, stack and heap memory.
- File Input Output Example Program in C — Program — write and read a text file.
- File Management — More in c advance.
Frequently Asked Questions
What does this C program do?
It is a C example program that demonstrates File Handling in C Programming (fopen, fprintf, fscanf, fclose), including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and conditional logic, illustrating a common pattern in C programming.