Opening and Closing Files in C
Open a file with "w" and its old contents are wiped instantly. Open it with "a" and new text goes at the end. Open a missing file with "r" and you get NULL. The mode string you pass to fopen decides all of this.
In this lesson you will learn all the fopen modes (r, w, a, r+, w+, a+ and their binary versions), see exactly what each does, and learn to close files correctly. Mode questions appear in nearly every C exam.
What You Will Learn
- The syntax of fopen and fclose.
- The three basic modes: r, w, a.
- The update modes: r+, w+, a+.
- Binary modes with b.
- What happens when the file does or doesn't exist.
- Why and how to close files.
Opening and Closing Files Explained
Exam definition: fopen(filename, mode) opens a file in the given mode and returns a FILE *, or NULL on failure. The mode tells whether the file is opened for reading, writing (truncating), or appending, and whether updating (+) or binary (b) access is used. fclose(fp) closes the file and returns 0 on success.
Memory trick: r = read a book from the library (it must exist). w = a whiteboard: wipe it, then write. a = attendance register: add new lines at the end, never erase. + = "also the other one" (read and write).
Syntax of fopen() and fclose()
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *fp); /* 0 = success, EOF = error */
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { /* not found / no permission */ }
fclose(fp);
fopen Modes Table
| Mode | Purpose | If file exists | If file doesn't exist | Position |
|---|---|---|---|---|
"r" | Read only | Opens it | Returns NULL | Start |
"w" | Write only | Erases contents | Creates it | Start |
"a" | Append only | Keeps contents | Creates it | Always writes at end |
"r+" | Read and write | Opens it (no erase) | Returns NULL | Start |
"w+" | Write and read | Erases contents | Creates it | Start |
"a+" | Read and append | Keeps contents | Creates it | Reads anywhere, writes at end |
- Add
bfor binary files:"rb","wb","ab","rb+"(or"r+b"),"wb+","ab+". - On Linux/macOS, text and binary modes behave the same. On Windows, text mode converts
\nto\r\n, so usebfor binary data. - C11 also adds
"x"(e.g."wx"): create a new file, but fail if it already exists, so nothing is overwritten by accident.
Example 1: w vs a (Overwrite vs Append)
#include <stdio.h>
void show(const char *name)
{
char line[80];
FILE *fp = fopen(name, "r");
if (fp == NULL)
{
printf(" (cannot open %s)\n", name);
return;
}
while (fgets(line, sizeof(line), fp) != NULL)
printf(" %s", line);
fclose(fp);
}
int main(void)
{
FILE *fp;
fp = fopen("log.txt", "w"); /* create */
fprintf(fp, "Day 1: learnt variables\n");
fclose(fp);
fp = fopen("log.txt", "a"); /* add at the end */
fprintf(fp, "Day 2: learnt loops\n");
fclose(fp);
printf("After w then a:\n");
show("log.txt");
fp = fopen("log.txt", "w"); /* wipe and write */
fprintf(fp, "Day 3: learnt pointers\n");
fclose(fp);
printf("After w again:\n");
show("log.txt");
remove("log.txt");
printf("Opening a missing file with r:\n");
show("log.txt");
return 0;
}
Output
After w then a: Day 1: learnt variables Day 2: learnt loops After w again: Day 3: learnt pointers Opening a missing file with r: (cannot open log.txt)
Code Explanation
"w"creates log.txt and writes Day 1."a"keeps Day 1 and adds Day 2 at the end.- Opening with
"w"again erases everything: only Day 3 remains. This is the most common file-handling accident. - After
remove, opening with"r"fails, sofopenreturns NULL andshowprints a message instead of crashing.
How the + Modes Work
The + modes allow both reading and writing on the same FILE pointer. One rule: when you switch between reading and writing, call a positioning function (fseek, rewind) or fflush in between.
"r+" file must exist; read and overwrite from the start; nothing erased
"w+" file emptied (or created); write first, rewind, then read
"a+" file kept (or created); read from anywhere, but every write goes to the end
Example 2: Using w+ and r+ (Read and Write on One Pointer)
#include <stdio.h>
int main(void)
{
FILE *fp;
char word[20];
int score;
fp = fopen("score.txt", "w+"); /* create, then read back */
if (fp == NULL)
return 1;
fprintf(fp, "Score 040\n");
rewind(fp); /* go back before reading */
fscanf(fp, "%19s %d", word, &score);
printf("w+ wrote and read: %s %d\n", word, score);
fclose(fp);
fp = fopen("score.txt", "r+"); /* open existing, update in place */
if (fp == NULL)
return 1;
fseek(fp, 6, SEEK_SET); /* jump to the digits */
fprintf(fp, "095"); /* overwrite 3 characters */
rewind(fp);
fscanf(fp, "%19s %d", word, &score);
printf("r+ updated to : %s %d\n", word, score);
fclose(fp);
remove("score.txt");
return 0;
}
Output
w+ wrote and read: Score 40 r+ updated to : Score 95
w+lets us write and then read back, afterrewindmoves the position to the start.r+opens the existing file without erasing it, so we can change just part of it.fseek(fp, 6, SEEK_SET)moves to byte 6 (the "040"). Random access is covered in a later lesson.
Closing Files: fclose and fcloseall
fclose(fp)writes any buffered data, frees the FILE structure and releases the file for other programs.- It returns 0 on success and EOF on error (for example, the disk is full).
- Don't use
fpafter closing it, and don't close the same pointer twice. - All open files are closed automatically when
mainreturns normally, but closing them yourself is good practice. (fcloseall()exists only in some compilers, so avoid it.)
Important Points to Remember
- r: read, file must exist.
- w: write, erases or creates.
- a: append at the end, keeps contents or creates.
- + adds the other operation (read and write).
- b = binary mode: rb, wb, ab…
- Between reading and writing in + modes, use fseek/rewind/fflush.
- fclose returns 0 on success; always close.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Using "w" to add records | Old records erased | Use "a" |
Using "r+" on a new file | fopen returns NULL | Use "w+" or "a+" |
Mode as a char: fopen("f.txt", 'r') | Compile error/crash | Mode is a string: "r" |
| Reading right after writing in w+ | Reads nothing (position at end) | rewind(fp) first |
| Text mode for binary data on Windows | Corrupted bytes | Use "rb" / "wb" |
File Modes Practice Questions
- What is the difference between
"w"and"a"? - What is the difference between
"r+"and"w+"? - Which modes return NULL if the file doesn't exist?
- Which mode would you use to add a new log entry every day?
- Write the mode to open an existing binary file for reading and writing.
Show answers
- "w" erases the file (or creates it) and writes from the start; "a" keeps the contents and writes at the end.
- Both read and write; "r+" needs an existing file and keeps its contents; "w+" creates or erases the file.
- "r" and "r+" (and their binary versions).
- "a" (append).
"rb+"(or"r+b").
Coding Exercise
Using "a" mode, append three expenses ("Tea 20", "Bus 35", "Lunch 120") to expenses.txt one at a time (open, write, close each time). Then read the file and print the total.
Show solution
#include <stdio.h>
void add(const char *item, int amount)
{
FILE *fp = fopen("expenses.txt", "a");
if (fp == NULL)
return;
fprintf(fp, "%s %d\n", item, amount);
fclose(fp);
}
int main(void)
{
FILE *fp;
char item[20];
int amount, total = 0;
remove("expenses.txt"); /* start fresh for the demo */
add("Tea", 20);
add("Bus", 35);
add("Lunch", 120);
fp = fopen("expenses.txt", "r");
if (fp == NULL)
return 1;
while (fscanf(fp, "%19s %d", item, &amount) == 2)
total += amount;
fclose(fp);
printf("Total spent: Rs %d\n", total);
remove("expenses.txt");
return 0;
}
Total spent: Rs 175
Quick Quiz: fopen() File Modes (MCQ)
-
Which mode erases an existing file?
A)
"r"B)"a"C)"w"D)"r+" -
Mode to add data at the end without erasing:
A)
"w"B)"a"C)"r"D)"w+" -
fopen("missing.txt", "r")returns:A) A new file B) NULL C) EOF D) 0 bytes
-
Mode to read and write an existing file without erasing it:
A)
"w+"B)"r+"C)"a"D)"w" -
fclose returns on success:
A) 1 B) 0 C) EOF D) NULL
Show answers
- C:
"w". - B:
"a". - B: NULL.
- B:
"r+". - B: 0.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| "r" | Read; file must exist |
|---|---|
| "w" | Write; erases or creates |
| "a" | Append at end; keeps or creates |
| "r+" | Read + write, must exist, no erase |
| "w+" | Write + read, erases or creates |
| "a+" | Read + append, writes at end |
| "b" | Binary version (rb, wb, ab) |
Frequently asked questions
- What is the difference between w and a mode?
- w erases the file and writes from the start; a keeps the contents and writes at the end.
- What is the difference between r+ and w+?
- r+ needs an existing file and keeps it; w+ creates or erases the file.
- What does fopen return if it fails?
- NULL, so always check it before using the pointer.
Remember
- r = library book, w = whiteboard, a = attendance register.
- + = also the other job.
Next Topic
Next lesson: Reading and Writing Text Files. You will read and write text files with fprintf, fscanf, fgets, fputs, fgetc and fputc.