File Handling in C (fopen, fscanf, fprintf)
#include <stdio.h>
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("Could not open file\n");
return 1;
}
// ...work with the file...
fclose(file);
fopen() returns a FILE * pointer used for all further operations on that file, or NULL if the file couldn't be opened — always check for this before proceeding.
FILE *file = fopen("data.txt", "w");
fprintf(file, "Score: %d\n", 95);
fputs("Second line of text\n", file);
fclose(file);
fprintf() works exactly like printf(), but writes to a file instead of the screen. fputs() writes a plain string without any formatting.
FILE *file = fopen("data.txt", "r");
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
fgets() reads one line at a time into your buffer, returning NULL once it reaches the end of the file — which is exactly what the while loop condition checks for.
"r"— read (file must already exist)"w"— write (creates new, or erases existing content first)"a"— append (adds to the end, existing content preserved)"r+"— read and write, without erasing existing content
Two very common file-handling mistakes: forgetting to call fclose(), which can leave data only partially written to disk and eventually exhausts your program's available file handles; and skipping the NULL check after fopen(), which causes a crash the instant you try to write to or read from a file that was never actually opened successfully.
Write a program that saves three lines of text to a file, then opens the same file again and prints its contents back to the screen.
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Could not open file\n");
return 1;
}
fprintf(file, "Learning C is fun\n");
fprintf(file, "File handling makes sense now\n");
fclose(file);
file = fopen("output.txt", "r");
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}