🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fopen Modes and fclose
Learn every fopen mode in C (r, w, a, r+, w+, a+, b and x), how to detect and report open errors, and how to close files safely. Runnable examples with real output.
The fopen modes in C decide what happens to your data the moment a file opens, and fclose is the door you must shut behind you. Pick the wrong mode and you can erase a file that took hours to collect. In this lecture of our free C programming course we study what each mode does to existing data, what the library does when opening fails, and how to handle errors the way professional embedded C programming code does. Everything is tested on Linux with gcc, so this free embedded C course gives you results you can reproduce.
What You Will Learn
- The signature of
fopenand what it returns - All fopen modes in C and what each does to existing data
- The effect of
band the C11xflag - Why
fopenfails and how to report the exact reason - How and why to call
fclose, and what its return value means - Portable path handling and open-file limits
Prerequisites
Lectures 1 to 3 of this chapter: streams, text versus binary, and buffering. You should also know that NULL is a pointer that points to nothing.
Opening a File with fopen
Before you can read or write a file you must open it, which means asking the library to connect your program to the file and give you a stream. fopen does this.
FILE *fopen(const char *filename, const char *mode);
It takes two strings. The first is the path of the file; the second tells the library what you intend to do. On success it returns a FILE * that identifies the stream. On failure it returns NULL and sets errno to describe the problem. From then on you use only the returned pointer; the file name is needed once, at open time.
FILE *cfg = fopen("device.cfg", "r");
FILE *log = fopen("run.log", "a");
The mode is a string, not a character
Write "w" with double quotes. Writing 'w' passes a number where a pointer is expected, which compiles only with a warning and crashes at run time. Compile with -Wall and you will catch it.
All fopen Modes in C
| Mode | Meaning | File must exist? | Existing data | Read | Write |
|---|---|---|---|---|---|
"r" | Read | Yes | Kept | Yes | No |
"w" | Write | No, created if missing | Erased (truncated to zero) | No | Yes |
"a" | Append | No, created if missing | Kept | No | Yes, always at the end |
"r+" | Read and update | Yes | Kept | Yes | Yes, in place |
"w+" | Write and read | No, created if missing | Erased | Yes | Yes |
"a+" | Append and read | No, created if missing | Kept | Yes | Yes, always at the end |
"w" destroys the old contents the instant fopen succeeds, before you write anything. If you meant to add to a log, you need "a".
The b flag and the C11 x flag
Add b for binary data. It may come after the base letter or after the plus sign, so "rb+" and "r+b" mean the same thing. Some compilers accept a t letter for text, but it is not part of standard C, so leave it out; text is already the default. C11 also added x for the write modes: "wx" fails if the file already exists instead of erasing it, which protects you from accidental overwrites.
| Mode string | Meaning |
|---|---|
"wb" | Binary file, write (truncate or create) |
"ab" or "a+b" | Binary file, append (the second also reads) |
"rb" | Binary file, read |
"r+" | Text file, update |
"wx" | Create new text file, fail if it exists |
Testing fopen Modes in C Yourself
This program applies several modes in sequence to one file and prints the content after each step. A newline is shown as | so you can see the structure.
#include <stdio.h>
#include <stdlib.h>
static void show(const char *tag, const char *path)
{
FILE *fp = fopen(path, "r");
if (fp == NULL) {
perror(path);
return;
}
char buf[64];
size_t n = fread(buf, 1, sizeof buf - 1, fp);
buf[n] = '\0';
for (size_t i = 0; i < n; i++)
if (buf[i] == '\n')
buf[i] = '|';
printf("%-22s -> [%s]\n", tag, buf);
fclose(fp);
}
static void put(const char *path, const char *mode, const char *text)
{
FILE *fp = fopen(path, mode);
if (fp == NULL) {
perror(path);
return;
}
fputs(text, fp);
fclose(fp);
}
int main(void)
{
const char *f = "modes.txt";
printf("FOPEN_MAX = %d, FILENAME_MAX = %d\n\n", FOPEN_MAX, FILENAME_MAX);
put(f, "w", "AAA\n");
show("after \"w\" AAA", f);
put(f, "a", "BBB\n");
show("after \"a\" BBB", f);
put(f, "w", "CCC\n");
show("after \"w\" CCC", f);
/* "r" is read only: writing must fail */
FILE *fp = fopen(f, "r");
if (fp != NULL) {
if (fputs("ZZZ\n", fp) == EOF)
printf("%-22s -> write refused\n", "fputs on \"r\" stream");
fclose(fp);
}
/* "r+" overwrites in place without erasing the rest */
fp = fopen(f, "r+");
if (fp != NULL) {
fputs("XX", fp);
fclose(fp);
}
show("after \"r+\" XX", f);
/* "r" on a missing file returns NULL */
fp = fopen("no_such_file.txt", "r");
if (fp == NULL)
perror("fopen no_such_file.txt");
/* C11 "x": fail instead of truncating an existing file */
fp = fopen(f, "wx");
if (fp == NULL)
perror("fopen modes.txt with wx");
return EXIT_SUCCESS;
}
$ gcc -Wall -Wextra -std=c11 -o modes modes.c
$ ./modes
FOPEN_MAX = 16, FILENAME_MAX = 4096
after "w" AAA -> [AAA|]
after "a" BBB -> [AAA|BBB|]
after "w" CCC -> [CCC|]
fputs on "r" stream -> write refused
after "r+" XX -> [XXC|]
fopen no_such_file.txt: No such file or directory
fopen modes.txt with wx: File exists
What the output shows
"w"replaced everything with the new text, and"a"added after the existing line.- The second
"w"threw away both earlier lines. - On this system a write to a read-only stream was refused. Portable code should still never rely on writing to
"r"streams. "r+"replaced only the first two characters; the rest (C|) stayed, so existing data is not erased in update mode.- The two error lines come from
perror, which turnserrnointo readable text.
Why fopen Fails
| Cause | Typical errno | Message you will see |
|---|---|---|
Opening a missing file with "r" or "r+" | ENOENT | No such file or directory |
| No permission to read or write | EACCES | Permission denied |
| Directory in the path does not exist | ENOENT | No such file or directory |
| Too many files already open | EMFILE | Too many open files |
Using "wx" on an existing file | EEXIST | File exists |
| Read-only filesystem (some flash setups) | EROFS | Read-only file system |
A safe open pattern
FILE *fp = fopen(path, "rb");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", path, strerror(errno));
return -1;
}
You need #include <errno.h> and #include <string.h> for this version. perror is shorter when you do not need a custom message.
fwrite, fflush or fclose, because the data was only buffered at open time. Check those return values as well.
Paths and limits
- On Linux use forward slashes:
"/home/pi/data/log.txt". In a C string a single backslash begins an escape sequence, so a Windows path needs doubled backslashes, for example"C:\\data\\log.txt". Windows also accepts forward slashes. FILENAME_MAXis the size a buffer needs to hold a file name; the real limits come from the filesystem and the OS.- The standard guarantees only a small minimum of simultaneously open files (
FOPEN_MAXis at least 8). On Linux the actual limit per process is set by the operating system; you can see it withulimit -n. - Close files you no longer need so you never hit that limit in a long-running daemon.
Closing a File with fclose
int fclose(FILE *stream);
When you finish with a file, close it. fclose writes out anything left in the buffer, releases the buffer, and breaks the connection between the program and the file. It returns 0 on success and EOF on failure. A failure at this point can mean your last data never reached the file, so for important files check it.
if (fclose(fp) != 0) {
perror("fclose");
/* the last buffered data may be lost */
}
fp = NULL; /* never use the old pointer again */
Rules for fclose
- Only close a pointer that
fopenreturned and that is notNULL. - Never close the same stream twice; the second call is undefined behaviour.
- Never use the stream after closing it.
- Closing is also the easiest way to flush, as covered in the buffering lecture.
- If a function can return early, close the file on every path or use a single cleanup label.
Common Mistakes with fopen Modes in C
| Mistake | Result | Fix |
|---|---|---|
Using "w" to add to a log | Old log erased on every start | Use "a" |
Using "r+" on a file that does not exist | fopen returns NULL | Create it first with "w" or use "a+" |
Using "w+" to modify existing data | Data erased on open | Use "r+" |
Passing 'w' instead of "w" | Warning and a crash | Use double quotes |
| Skipping the NULL check | Segmentation fault | Test every fopen |
Forgetting to switch between read and write on + modes | Undefined behaviour | After writing, call fflush or fseek before reading; after reading, call fseek before writing |
Best Practices
- Among all fopen modes in C, choose the least powerful one that does the job: read-only data gets
"r". - Use
"wx"when overwriting would be a bug. - Write the file name into every error message.
- Pair each
fopenwith exactly onefclose. - For safe updates of important files on embedded Linux, write to a temporary file, flush, then use
renameto replace the original.
Security consideration
Never build a path directly from untrusted input such as a network message or command-line argument without checking it, because it may point somewhere you did not intend. Also avoid checking whether a file exists and then opening it as two steps; use "wx" so the check and the creation happen together.
Key Takeaways
fopen(path, mode)returns aFILE *orNULL.- The fopen modes in C are easy to remember:
"w"erases,"a"appends,"r"reads, and the plus forms allow both reading and writing. bmarks binary;x(C11) refuses to overwrite.- Always test for
NULLand reporterrnowithperrororstrerror. fcloseflushes and releases the stream; check its return value for important data.
You now know every fopen mode in C and how to close files properly. The last lecture of this chapter section puts everything together in a hands-on lab and finishes with a quiz and interview questions.
Frequently Asked Questions
What are the fopen modes in C?
The base modes are "r", "w", "a", "r+", "w+" and "a+". Add b for binary and, in C11, x to refuse overwriting an existing file in the write modes.
What does fopen return in C?
A pointer of type FILE * on success, or NULL if the file could not be opened.
What is the difference between “w” and “a” in fopen?
"w" erases existing content or creates the file; "a" keeps the content and adds all new writes at the end.
What is the difference between “r+” and “w+”?
Both allow read and write. "r+" requires the file to exist and keeps its data; "w+" creates or empties the file.
How do I find out why fopen failed?
Check for NULL, then call perror("name") or print strerror(errno).
Do I need to call fclose?
Yes. It flushes buffered data, frees resources, and its return value tells you whether the final write succeeded. Normal exit closes streams, but relying on that is poor practice.
What does the x in “wx” do?
Added in C11, it makes fopen fail if the file already exists, so you cannot overwrite it by accident.
How many files can I open at once in C?
The standard guarantees at least FOPEN_MAX (minimum 8). The practical limit on Linux is set by the operating system, viewable with ulimit -n.
Finish the lab in our free embedded C course
Next: a sensor logging lab, a quiz and interview questions to lock in Chapter 11 basics.

2 Comments