C Files
Variables disappear when a program ends. To keep data — settings, scores, logs, documents — you write it to a file, and read it back the next time. C handles files through the same <stdio.h> header you already use for printf, with a type called FILE and a handful of functions.
The basic workflow is always the same:
- Open the file with
fopen, which returns aFILE *(orNULLon failure). - Read or write with functions such as
fprintf,fputs,fgetsandfscanf. - Close it with
fcloseso the data is flushed to disk and resources are released.
Opening a file: modes
FILE *fp = fopen("filename.txt", "mode");| Mode | Meaning | If the file exists | If it doesn't |
|---|---|---|---|
"r" |
read | read from the start | fails (NULL) |
"w" |
write | erases its contents | creates it |
"a" |
append | writes at the end | creates it |
"r+" |
read and write | keeps contents | fails |
"w+" |
read and write | erases contents | creates it |
"a+" |
read and append | writes at the end | creates it |
Add b (e.g. "rb", "wb") for binary files. On Linux and macOS it makes no difference; on Windows it disables newline translation.
Writing to a file
fprintf works exactly like printf, but takes the file as its first argument. fputs writes a plain string:
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
printf("Could not open notes.txt for writing\n");
return 1;
}
fprintf(fp, "Shopping list\n");
fprintf(fp, "%d x %s\n", 6, "eggs");
fprintf(fp, "%d x %s\n", 2, "milk");
fputs("1 x bread\n", fp);
fclose(fp);
printf("File written.\n");
return 0;
}File written.
This creates notes.txt in the program's current directory. Always check fopen's result: it fails when the folder does not exist, you lack permission, or (for "r") the file is missing.
Reading a file line by line
fgets(buffer, size, fp) reads one line (up to size - 1 characters) into buffer and returns NULL at the end of the file. A while loop around it processes the whole file:
#include <stdio.h>
int main(void) {
// First create a small file to read
FILE *out = fopen("poem.txt", "w");
if (out == NULL) return 1;
fputs("Roses are red,\nviolets are blue,\nC has pointers\nand so can you.\n", out);
fclose(out);
FILE *in = fopen("poem.txt", "r");
if (in == NULL) {
printf("Could not open poem.txt\n");
return 1;
}
char line[100];
int number = 1;
while (fgets(line, sizeof line, in) != NULL) {
printf("%d: %s", number, line); // line already ends with '\n'
number++;
}
fclose(in);
remove("poem.txt"); // delete the file again
return 0;
}1: Roses are red,
2: violets are blue,
3: C has pointers
4: and so can you.
remove(filename) deletes a file; rename(old, new) renames one. Both return 0 on success.
Appending
Mode "a" adds to the end without destroying what is already there — perfect for log files:
#include <stdio.h>
void log_message(const char *msg) {
FILE *fp = fopen("app.log", "a");
if (fp == NULL) return;
fprintf(fp, "[log] %s\n", msg);
fclose(fp);
}
int main(void) {
remove("app.log"); // start fresh for this demo
log_message("program started");
log_message("loaded 3 users");
log_message("program finished");
FILE *fp = fopen("app.log", "r");
if (fp == NULL) return 1;
char line[80];
while (fgets(line, sizeof line, fp)) {
fputs(line, stdout);
}
fclose(fp);
return 0;
}[log] program started
[log] loaded 3 users
[log] program finished
stdout is itself a FILE * — the screen. fputs(line, stdout) and fprintf(stdout, ...) print to the terminal.
Reading structured data with fscanf
When a file contains values in a known format, fscanf parses them like scanf does. Its return value tells you how many fields were read, which is how you detect the end of the data:
#include <stdio.h>
int main(void) {
FILE *fp = fopen("scores.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "alice 82\nbob 95\ncarol 78\n");
fclose(fp);
fp = fopen("scores.txt", "r");
if (fp == NULL) return 1;
char name[32];
int score, total = 0, count = 0;
while (fscanf(fp, "%31s %d", name, &score) == 2) {
printf("%-6s %3d\n", name, score);
total += score;
count++;
}
fclose(fp);
printf("average: %.1f\n", (double) total / count);
remove("scores.txt");
return 0;
}alice 82
bob 95
carol 78
average: 85.0
File function reference
| Function | Purpose |
|---|---|
fopen(name, mode) |
open a file, returns FILE * or NULL |
fclose(fp) |
close it (flushes buffered data) |
fprintf(fp, fmt, ...) |
formatted write |
fputs(str, fp) / fputc(ch, fp) |
write a string / a character |
fgets(buf, n, fp) |
read a line, NULL at end of file |
fgetc(fp) |
read one character, EOF at the end |
fscanf(fp, fmt, ...) |
formatted read, returns number of items read |
fread / fwrite |
read / write raw binary blocks |
feof(fp), ferror(fp) |
check why a read stopped |
remove(name), rename(old, new) |
delete / rename a file |
Tip: Every successful
fopenneeds exactly onefclose. Forgetting it can lose the last data you wrote (it may still be in a memory buffer) and leaks a file handle.
Test yourself
What happens when you open an existing file with mode "w"?
- New data is added at the end
- Its contents are erased
- fopen fails
- The file is opened read-only
What does fopen return when it cannot open the file?
- 0 as an int
- NULL
- EOF
- An empty FILE
What does fgets return when it reaches the end of the file?
- An empty string
- EOF
- NULL
- -1