C File Handling Introduction
In this page:
Introduction to Files
This persistence is exactly why programs use files for anything that needs to survive a restart -- configuration settings, saved game progress, or logs are all stored this way rather than only living in the program's in-memory variables.
Example: Introduction to Files
#include <stdio.h>
int main() {
FILE *fp = fopen("notes.txt", "w");
fprintf(fp, "Saved data");
fclose(fp);
printf("Data persisted to a file");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
File Streams in C
The FILE pointer (returned by fopen()) is an opaque handle -- you never need to know its internal structure, only to pass it consistently to every file function (fread, fwrite, fclose, etc.) that operates on that particular open file.
Example: File Streams in C
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello");
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Standard Streams vs Files
stdin, stdout, and stderr are actually already-open FILE pointers that your program receives automatically at startup, which is why functions like printf() (which writes to stdout) don't require you to open anything first.
Example: Standard Streams vs Files
#include <stdio.h>
int main() {
printf("This goes to stdout automatically");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Basic File operations
Skipping the close step risks losing buffered data that hasn't been physically written to disk yet, since many I/O operations are buffered in memory for performance and only flushed to disk at certain points, including when the file closes.
Example: Basic File operations
#include <stdio.h>
int main() {
FILE *fp = fopen("log.txt", "w");
fprintf(fp, "entry");
fclose(fp);
printf("Closed the file");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Checking file existence
This is a common lightweight pattern for existence checks, though it has a side effect: if the file does exist, you've now opened it and must remember to close it again, or you'll leak a file handle.
Example: Checking file existence
#include <stdio.h>
int main() {
FILE *fp = fopen("maybe.txt", "r");
if (fp != NULL) {
printf("File exists");
fclose(fp);
} else {
printf("File does not exist");
}
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: