1. Introduction
File handling in C lets a program read from and write to files stored on disk, so data can persist beyond the lifetime of the running process. The standard I/O library (stdio.h) provides a FILE pointer abstraction and a set of functions — fopen(), fclose(), fprintf(), fscanf(), fgets(), fputs(), fread(), and fwrite() — that work uniformly whether the underlying stream is a text file, a binary file, or even standard input/output. Mastering file handling is essential for tasks such as logging, configuration parsing, data serialization, and building command-line utilities.
Cricket analogy: File handling is like recording a match's scorecard on paper so the result persists after the players leave the ground, with fopen/fclose acting like opening and closing the official scorebook for entries.
2. Syntax
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);3. Explanation
fopen() opens a file and returns a FILE* handle, or NULL if the operation fails (e.g., the file does not exist in read mode, or permissions are insufficient). The mode string controls behavior: "r" opens an existing file for reading, "w" creates a new file for writing (truncating an existing one), "a" opens for appending (writing at the end, creating the file if absent), and "r+", "w+", "a+" add read/update capability. Appending a "b" (e.g., "rb", "wb") opens the file in binary mode, which matters on platforms that translate newline characters in text mode. Once open, fprintf()/fscanf() perform formatted text I/O similar to printf()/scanf(), while fread()/fwrite() move raw bytes for binary records. fclose() flushes any buffered output and releases the FILE* handle back to the OS; every successfully opened file must eventually be closed.
Cricket analogy: fopen's "r" mode is like reviewing an existing scorecard without altering it, "w" is like starting a fresh scorecard that erases the old one, and "a" is like adding new overs to the end of today's card; a "b" suffix is like recording raw ball-by-ball sensor data instead of readable text, and fclose is like officially signing off and submitting the card.
4. Example
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
perror("fopen failed");
return 1;
}
fprintf(fp, "Line 1: Hello, file!\n");
fprintf(fp, "Line 2: %d + %d = %d\n", 2, 3, 5);
fclose(fp);
fp = fopen("notes.txt", "r");
if (fp == NULL) {
perror("fopen failed");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}5. Output
Line 1: Hello, file!
Line 2: 2 + 3 = 5Always check the return value of fopen() for NULL before using the FILE pointer — writing or reading through a NULL pointer causes undefined behavior. Just as important: always call fclose() on every file you open, even along error-return paths, otherwise buffered writes may never reach disk and you leak file descriptors.
Use "a" mode instead of "w" when you want to preserve existing file content and add new data at the end — "w" mode silently truncates the file to zero length first.
6. Key Takeaways
- fopen() returns a FILE* or NULL on failure — always check before use.
- Mode strings ("r", "w", "a", plus "+" and "b" variants) control read/write/append and text/binary behavior.
- fprintf/fscanf handle formatted text; fread/fwrite handle raw binary records.
- fclose() flushes buffers and releases the handle — never skip it.
- "w" truncates an existing file; "a" appends without truncating.
Practice what you learned
1. What does fopen() return if the specified file cannot be opened?
2. Which mode opens a file for writing, creating it if it doesn't exist and truncating it if it does?
3. Which function is most appropriate for reading raw binary records (e.g., an array of struct) from a file?
4. What is the primary purpose of calling fclose() on an open file?
5. Which mode string opens a file for appending, creating it if it does not already exist?
Was this page helpful?
You May Also Like
Strings in C
Master C strings: null-terminated char arrays, string literals vs char arrays, key string.h functions, and buffer-overflow pitfalls.
Pointers in C
Learn C pointers with syntax, address-of and dereference operators, pointer arithmetic, and common pitfalls, with examples and output.
Structures in C
Understand C structures: syntax, dot vs arrow member access, nested structs, and why sizeof() can exceed the sum of member sizes due to padding.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics