File Handling Basics
Every variable, array, and struct you have used so far lives only in memory — the moment the program exits, it is gone. File I/O is how a C program persists data beyond its own execution: writing results to disk so they survive after the process ends, and reading them back later, possibly from an entirely different run of the program (or a different program altogether).
The FILE* Abstraction
The C standard library (<stdio.h>) represents an open file with an opaque type called FILE. You never touch a FILE directly — you always work through a pointer to it, FILE *, which the library hands you when you open a file and which you pass to every subsequent read, write, or close operation.
#include <stdio.h>
int main(void)
{
FILE *fp; /* a handle to an open file, not the file's data itself */
fp = fopen("notes.txt", "w");
if (fp == NULL) {
printf("Could not open file.\n");
return 1;
}
fprintf(fp, "Persisted to disk.\n");
fclose(fp);
return 0;
}Think of FILE * as a handle or ticket, not the file's actual bytes — it tracks bookkeeping like the current read/write position, internal buffers, and error/EOF state on your behalf.
The General Workflow
Open the file with
fopen(), specifying a path and a mode (read, write, append, ...)Read or write through the returned
FILE *, using functions likefprintf,fscanf,fgets,fread,fwrite, and friendsClose the file with
fclose()once you are done, releasing the underlying resource and flushing any buffered writes to disk