🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fclose in C: Closing Files
What closing a file really does, why it can fail, and how to stop leaking file handles in embedded C programs.
Every file you open in a C program is a small contract with the operating system, and fclose() is the line that ends it. In this lecture of our free C programming course you will learn how fclose in C works, what it flushes, what it returns, and why forgetting it quietly breaks embedded programs. We keep the explanations simple, but we also look at the corner cases that surprise even experienced developers.
The old textbook this series is based on describes closing a file in one short page. That is fine for DOS-era exercises, but modern C for embedded systems has to cope with Linux file systems, SD cards that can disappear, tiny C libraries with a handful of file slots, and flash storage that can run out of space at the worst moment. Every program below was compiled with gcc -Wall -Wextra and run on a current Linux system, and the output you see is the real output.
What You Will Learn
By the end of this free C tutorial you can:
- Explain what fclose in C does to the stdio buffer, the FILE object and the file descriptor.
- Check the return value of
fclose()and know when a failure means lost data. - Show with a program that skipping
fclose()leaks file handles. - Understand why
fcloseall()is not portable and when it is dangerous. - Apply a close-everything-exactly-once pattern in embedded C programming.
Prerequisites
You should already be comfortable with fopen(), the file modes r, w and a, and the idea of a buffer between your program and the disk, all covered in the earlier lectures of this free embedded C course. A Linux machine (or WSL) with gcc is enough to run every example.
How fclose in C Works Behind the Scenes
When you call fopen(), the C library allocates a FILE object, asks the operating system for a file descriptor and usually allocates a buffer of a few kilobytes. Your calls to fputs() or fprintf() do not go to the disk one by one. They copy bytes into that buffer, and the buffer is written out in one larger operation when it fills up, when you call fflush(), or when the stream is closed.
What fclose() does, step by step
So fclose in C is not just housekeeping. Its first and most important job is the flush: any bytes still sitting in your buffer are handed to the operating system. Only after that does it release the descriptor and free the memory. For a stream opened for reading, buffered input that was never consumed is simply discarded.
fclose in C: Syntax, Return Value and Errors
int fclose(FILE *stream);
| Return value | Meaning | What you should do |
|---|---|---|
0 | Buffer flushed and stream closed. | Carry on. Do not use the pointer again. |
EOF (normally -1) | An error was detected while flushing or closing. The stream is still gone. | Report it with perror(). Treat the file as possibly incomplete. |
Notice the second row. Even when fclose() fails, the stream is no longer valid. You cannot retry the call. The usual causes are a full file system, an input/output error from the device, or removable media that was pulled out. The old book mentions the last two reasons almost in passing, but on an embedded board they are everyday events.
A first complete program
The program below creates a small log, closes it with a checked fclose(), reopens it in append mode, adds a second line and prints the result. Save it as ep_close.c.
#include <stdio.h>
#include <stdlib.h>
/* Close explicitly, check the result, then reopen in append mode. */
int main(void)
{
FILE *fp = fopen("boot.log", "w");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
fputs("kernel up\n", fp);
if (fclose(fp) == EOF) {
perror("fclose");
return EXIT_FAILURE;
}
puts("step 1: boot.log closed, buffer flushed to disk");
fp = fopen("boot.log", "a");
if (fp == NULL) {
perror("fopen append");
return EXIT_FAILURE;
}
fputs("uart ready\n", fp);
fclose(fp);
fp = fopen("boot.log", "r");
if (fp == NULL) {
perror("fopen read");
return EXIT_FAILURE;
}
char line[64];
int n = 0;
while (fgets(line, sizeof line, fp) != NULL) {
n++;
printf("line %d: %s", n, line);
}
fclose(fp);
return EXIT_SUCCESS;
}
Build and run it:
gcc -Wall -Wextra -o ep_close ep_close.c
./ep_close
Expected output:
step 1: boot.log closed, buffer flushed to disk
line 1: kernel up
line 2: uart ready
Two things are worth noticing. First, the return value of fclose() is compared with EOF, not with a bare -1, so the code stays correct on any compiler. Second, the file is opened three times and closed three times; every fopen() has exactly one matching fclose(). That one-to-one habit prevents most file bugs.
fclose can fail even when every write looked fine
This is the point most tutorials skip. Writing functions such as fputs() only fill the buffer, so they usually succeed. The real error appears later, when the buffer is flushed. Linux provides a special device, /dev/full, that behaves like a storage device with no space left, which makes it perfect for testing this.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
/* /dev/full always reports "no space left", like a flash card that is full.
* The write calls look fine because they only fill the stdio buffer.
* Only fclose() (which flushes) tells the truth. */
int main(void)
{
FILE *fp = fopen("/dev/full", "w");
if (fp == NULL) {
perror("/dev/full");
return EXIT_FAILURE;
}
int rc = fputs("sensor=42\n", fp);
printf("fputs returned %d (%s)\n", rc, rc >= 0 ? "looks fine" : "failed");
if (fclose(fp) == EOF)
printf("fclose failed: %s\n", strerror(errno));
else
puts("fclose succeeded");
return 0;
}
gcc -Wall -Wextra -o ep_devfull ep_devfull.c
./ep_devfull
fputs returned 1 (looks fine)
fclose failed: No space left on device
The write call reported success, yet the data never reached the device. If this program had ignored the result of fclose(), your product would have told the user that a calibration file was saved when it was not. In embedded C programming, always check the close.
Why Close Files Explicitly
At normal program termination, through return from main() or a call to exit(), the C runtime flushes and closes every open stream. That convenience tempts beginners to skip fclose(). The table shows why you should not.
| Situation | Is buffered data saved without fclose? | Comment |
|---|---|---|
Return from main() or exit() | Yes | The runtime closes every stream for you. |
abort() or a crash (for example a bad pointer) | Not guaranteed | Behaviour is implementation-defined; do not rely on it. |
| Process killed by a signal such as SIGKILL | No | Nothing runs; the buffer is lost. |
| Power cut or watchdog reset | No | The buffer lives in RAM only. |
| Another part of the program needs the same file | Not until it is flushed or closed | Reopening for reading before closing may show a half-written file. |
Four good reasons follow from this:
- Data safety: the flush happens at a moment you control, not at the mercy of a crash.
- Error reporting: only an explicit call lets you read the return value.
- Resource limits: descriptors and buffers are scarce, as the next section proves.
- Changing the mode: to switch a file from write to read you must close it and open it again.
Leaking Streams: Running Out of File Handles
A leak means a stream that is opened but never closed. One leaked file does no visible harm, which is exactly why the bug survives testing. A service that leaks one handle per minute fails after the limit is reached, perhaps weeks into deployment. The next program lowers the limit to 16 so you can watch it happen in a split second.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/resource.h>
#define MAX_TRACK 64
/* Lower the per-process descriptor limit so the leak shows up quickly. */
static void shrink_limit(rlim_t n)
{
struct rlimit rl;
getrlimit(RLIMIT_NOFILE, &rl);
rl.rlim_cur = n;
setrlimit(RLIMIT_NOFILE, &rl);
}
int main(void)
{
FILE *held[MAX_TRACK];
int count = 0;
shrink_limit(16);
while (count < MAX_TRACK) {
held[count] = fopen("/etc/hostname", "r");
if (held[count] == NULL)
break;
count++;
}
printf("opened %d streams before failure\n", count);
printf("reason: %s\n", strerror(errno));
for (int i = 0; i < count; i++)
fclose(held[i]);
FILE *again = fopen("/etc/hostname", "r");
printf("after closing all: fopen %s\n", again ? "works again" : "still fails");
if (again)
fclose(again);
return 0;
}
gcc -Wall -Wextra -o ep_leak ep_leak.c
./ep_leak
opened 13 streams before failure
reason: Too many open files
after closing all: fopen works again
Sixteen descriptors minus the three standard ones leaves thirteen for the program. Once the thirteenth is taken, fopen() returns NULL and errno reads EMFILE. After the loop closes everything, opening works again. The lesson for fclose in C is simple: handles are a renewable resource only if you hand them back.
Handle budget of a small program
Limits you should know
ISO C guarantees only that at least 8 files can be open at once (FOPEN_MAX, which is 16 with glibc on the test machine). Linux commonly allows 1024 descriptors per process, but small C libraries used with microcontroller file systems may allow only a few. Design for the small number.
Closing Many Files and the fcloseall() Trap
When several files are open, close each with its own call, ideally in the reverse order of opening. The book also mentions fcloseall(), which closes every open stream at once. It is tempting, but it is not part of ISO C. It is a GNU extension, so you must define _GNU_SOURCE to see it, and other compilers behave differently.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* fcloseall() is a GNU extension: it also closes stdin, stdout and stderr. */
int main(void)
{
FILE *a = fopen("a.txt", "w");
FILE *b = fopen("b.txt", "w");
FILE *c = fopen("c.txt", "w");
if (!a || !b || !c)
return EXIT_FAILURE;
fputs("alpha\n", a);
fputs("beta\n", b);
fputs("gamma\n", c);
int rc = fcloseall();
/* stdout is closed now, so printf would be lost; use write(2) instead */
char msg[80];
int len = snprintf(msg, sizeof msg, "fcloseall returned %d\n", rc);
write(STDOUT_FILENO, msg, (size_t)len);
const char *tail = "printf after fcloseall is not safe\n";
write(STDOUT_FILENO, tail, strlen(tail));
return 0;
}
gcc -Wall -Wextra -o ep_closeall ep_closeall.c
./ep_closeall
cat a.txt b.txt c.txt
fcloseall returned 0
printf after fcloseall is not safe
alpha
beta
gamma
| Point | Old compiler books | glibc on Linux |
|---|---|---|
| Return value on success | Number of files closed | 0 |
| Return value on error | EOF | EOF |
| Closes stdin, stdout, stderr too? | Usually no | Yes, all of them |
| Standard C? | No | No (GNU extension) |
Look at the program: after fcloseall() it uses write() instead of printf(), because stdout itself is gone. Code copied from an old book that checks “returns the number of files closed” would misreport on Linux. The portable answer is to keep your own handles and close them one at a time.
A tidy cleanup pattern
For functions that open several files, set each pointer to NULL at the start, jump to one cleanup block on any error, and close only the pointers that are not NULL. The cleanup block is the single place where every fclose() lives, so none can be forgotten. After each close, assign NULL so a repeated close is impossible.
Real-World Embedded Uses
- Event logs on an SD card: a Linux-based gateway appends sensor readings, closing the file on every rotation so a power cut loses at most the last record.
- Configuration save: write to a temporary file, check
fclose(), then rename over the old file. A failed close means you keep the old, valid configuration. - Firmware update staging: a downloaded image is written to flash storage and verified only after a successful close.
- Reading sysfs and proc files: a monitoring daemon opens, reads and closes a temperature file every second. Missing the close would exhaust descriptors in minutes.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Never calling fclose() | Too many open files after a long run | Pair every fopen() with one fclose(). |
| Ignoring the return value | Program says “saved” but the file is short | Compare with EOF and call perror(). |
| Using the pointer after closing | Random crashes or garbage | Assign NULL after closing. |
| Closing twice | Undefined behaviour, sometimes a heap-corruption abort | Close only in the cleanup block. |
Calling fclose(NULL) | Crash | Test the pointer first; fopen() may have failed. |
| Relying on exit to flush after a crash | Last lines missing from the log | Flush or close at known safe points. |
Best Practices for fclose in C
- Close a file as soon as the last operation on it is done; do not hold it open for convenience.
- Check the result of
fclose()for every file you wrote to. For files you only read, ignoring it is acceptable. - Set the pointer to
NULLafter closing. - On POSIX systems that need power-fail safety, use
fflush()andfsync(fileno(fp))before the final close. - Keep every file’s open and close in the same function or the same module, so a reader can see the pairing.
Performance considerations
Closing flushes, and a flush is a real write to the file system. Closing and reopening a log file for every single line multiplies those writes, which wastes time and wears flash memory. A common compromise is to keep the log open, call fflush() after important events, and close it on rotation or shutdown.
Security considerations
A descriptor leak that an outside party can trigger, for example by sending many requests that each open a file, becomes a denial-of-service bug. A use-after-close is undefined behaviour and, in the worst case, can be exploited. Setting pointers to NULL after closing is a cheap defence.
Key Takeaways
Remember these points
- fclose in C flushes the buffer, closes the descriptor and frees the FILE object.
- It returns 0 on success and
EOFon error. Errors from earlier buffered writes surface here. - A stream is invalid after the call, even when the call fails.
- Normal exit closes files for you; a crash or power loss does not.
fcloseall()is a non-standard GNU extension that also closes stdout. Avoid it.- Every
fopen()needs exactly onefclose().
Conclusion
Closing a file looks like the least interesting line in a program, yet it is where buffered data becomes real, where write errors finally show themselves, and where scarce handles come back to the pool. In this lecture you saw the flush happen, watched a leak exhaust the handle table, caught a write failure that only fclose() reported, and learned why the book’s fcloseall() advice does not carry over to Linux.
Carry these habits into every embedded project: pair opens with closes, check the result, and null the pointer. In the next lecture of this free C programming course we look at how a program knows that it has reached the end of a file, and why EOF is not a character stored in the file.
Frequently Asked Questions
Is fclose in C mandatory if the program is about to exit?
At normal termination the C runtime flushes and closes every open stream for you. Closing explicitly is still the right habit because the program may be changed later, because abnormal exits such as a crash or power cut do not flush buffers, and because only an explicit fclose() lets you see and handle a write error.
What does fclose return?
It returns 0 when the stream was closed successfully and EOF (a negative value, normally -1) when an error was detected. The error can come from flushing the last buffered data, so a failure often means the end of your file was not saved.
Can I use a FILE pointer after calling fclose?
No. After a successful or failed call the pointer value is indeterminate and any use, including a second fclose(), is undefined behaviour. Set the pointer to NULL right after closing so mistakes show up as a clean crash instead of silent corruption.
Does fclose guarantee the data is physically on the disk or flash chip?
No. It pushes the data from the stdio buffer to the operating system. The kernel may still hold it in its page cache. For power-fail safety call fflush() followed by fsync(fileno(fp)) before closing, on systems that provide POSIX.
Is fcloseall() part of standard C?
No. It is a GNU extension found in glibc and some older compilers. Its return value differs between implementations and the glibc version also closes stdin, stdout and stderr. Close your own streams one by one instead.
How many files can I keep open at once?
ISO C only promises at least 8 (the FOPEN_MAX macro, which is 16 with glibc). Linux additionally limits descriptors per process, commonly 1024. Small embedded C libraries may allow far fewer, so always close files as soon as you are done.
What happens if I never call fclose on a file opened for reading?
Nothing is lost, but the stream and its descriptor stay allocated until the program ends. A long-running embedded service that opens a configuration file every few seconds will eventually fail with Too many open files.
Keep Going With the Free Embedded C Course
Continue with end-of-file handling, character input and output, and a hands-on logging lab. Every lecture in this free C tutorial is tested on a real compiler.
<
2 Comments