The maximum number of open files
What you'll learn: How to determine and respect the limit on how many files your program can have open at the same time.
Imagine you are a librarian. You can handle many books, but you only have so much desk space. If your desk is covered in open books, you can't open a new one until you close and set aside one that you are finished with. In C, your operating system acts like that desk. It sets a strict limit on how many "file pointers" you can have active at once.
Why is there a limit?
Every time you use fopen(), the system allocates a small amount of memory to track that file's progress—where you are reading, what buffers are being used, and what permissions you have. These resources are finite. If a program could open millions of files without closing them, it would eventually crash the program or even slow down the entire computer.
Most systems define a constant called FOPEN_MAX. This is a guaranteed minimum number of files you can have open simultaneously. On many modern systems, this is often 16 or 20, though the actual technical limit might be much higher.
Checking the limit
You can actually see what your specific environment guarantees by printing the FOPEN_MAX constant found in the <stdio.h> library.
#include <stdio.h>
int main() {
// Print the system-defined maximum for open files
printf("This system guarantees you can open %d files at once.\n", FOPEN_MAX);
// Note: This includes the 3 files already open for you:
// stdin, stdout, and stderr!
return 0;
}
The "File Leak"
The most common mistake beginners make is opening a file inside a loop but forgetting to call fclose(). This creates a "file leak." Just like a water leak fills a bucket, a file leak fills up your "desk space." Eventually, fopen() will start returning NULL, not because the file doesn't exist, but because you've hit your limit.
Always treat your file pointers like borrowed tools: pick them up, use them, and put them back immediately so you don't run out of room.
Key takeaway
Every system has a maximum capacity for open files (FOPEN_MAX); always use fclose() to free up space for new files.