C fopen() & fclose()
In this page:
Opening a file with fopen()
Common modes include "r" (read), "w" (write, truncating existing content), and "a" (append) -- always check the returned pointer against NULL before using it, since a missing file or insufficient permissions will cause fopen() to fail silently otherwise.
Example: Opening a file with fopen()
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Failed to open");
return 1;
}
fprintf(fp, "Hello");
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Closing a file with fclose()
Beyond just flushing buffered writes, forgetting to close files can eventually exhaust the operating system's limit on how many files a single process can have open simultaneously, causing later fopen() calls to start failing.
Example: Closing a file with fclose()
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello");
fclose(fp);
printf("Closed properly");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading modes ("r", "rb")
Text mode (r) may perform platform-specific newline translation (like converting \r\n to \n on Windows), which corrupts binary data such as images -- binary mode (rb) disables this translation and reads bytes exactly as stored.
Example: Reading modes ("r", "rb")
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello");
fclose(fp);
fp = fopen("data.txt", "r");
char buffer[10];
fgets(buffer, 10, fp);
printf("%s", buffer);
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Writing modes ("w", "wb", "a")
w mode silently destroys any existing file content the moment you open it, even before you write anything -- if you need to preserve existing data while adding to it, a mode is the safer choice.
Example: Writing modes ("w", "wb", "a")
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "First");
fclose(fp);
fp = fopen("data.txt", "a");
fprintf(fp, "Second");
fclose(fp);
printf("Appended without erasing");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Managing multiple open files
Each FILE pointer independently tracks its own read/write position within its file, so operations on one open file have no effect on another -- just make sure every fopen() call you make has a corresponding fclose() eventually.
Example: Managing multiple open files
#include <stdio.h>
int main() {
FILE *fp1 = fopen("a.txt", "w");
FILE *fp2 = fopen("b.txt", "w");
fprintf(fp1, "File A");
fprintf(fp2, "File B");
fclose(fp1);
fclose(fp2);
printf("Both files written independently");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: