Fopen without fclose in C

What happens if I open a file using fopen several n times without invoking fclose on it?

Having problems with buffer overflows?

+4
source share
5 answers

If you continue fopen without fclose , then your future fopen calls will fail. A limited number of file descriptors are available for your program.

See this related SO question .

+12
source

You are losing core files. Please close all files that you open in a timely manner to avoid this resource leak.

+5
source

If you continue to open files without closing them, you will at some point run out of file descriptors either at the application level or at the OS level, and all further attempts to open the file will fail.

+1
source

Besides losing the file descriptors for the process, as others answered, you also lose memory, as each file stream manages the I / O buffers that are allocated inside libc .

0
source

As already mentioned, you do not want to lose file descriptors. But it is normal that one file is opened several times. The file descriptors are independent and will not interfere with each other (assuming that you are just reading and not writing to the file).

 #include <stdio.h> int main() { FILE* f1 = fopen("/tmp/foo.txt", "rb"); FILE* f2 = fopen("/tmp/foo.txt", "rb"); FILE* f3 = fopen("/tmp/foo.txt", "rb"); FILE* f4 = fopen("/tmp/foo.txt", "rb"); char buf1[32] = { 0, }; char buf2[32] = { 0, }; char buf3[32] = { 0, }; char buf4[32] = { 0, }; fread(buf1, 1, sizeof(buf1) - 1, f1); fread(buf2, 1, sizeof(buf2) - 1, f2); fread(buf3, 1, sizeof(buf3) - 1, f3); fread(buf4, 1, sizeof(buf4) - 1, f4); printf("buf1 = '%s'\n", buf1); printf("buf2 = '%s'\n", buf2); printf("buf3 = '%s'\n", buf3); printf("buf4 = '%s'\n", buf4); fclose(f1); fclose(f2); fclose(f3); fclose(f4); return 0; } 

Gives output, for example:

 $ ./fopen buf1 = '0123456789ABCDEFGHIJ0123456789a' buf2 = '0123456789ABCDEFGHIJ0123456789a' buf3 = '0123456789ABCDEFGHIJ0123456789a' buf4 = '0123456789ABCDEFGHIJ0123456789a' 
0
source

All Articles