Why doesn't calling close () after fopen () close?

I looked at the following code in one of our internal libraries, and I'm trying to understand the behavior that it showed:

long GetFD(long* fd, const char* fileName, const char* mode) { string fileMode; if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o') fileMode = string("w"); else if (tolower(mode[0]) == 'a') fileMode = string("a"); else if (tolower(mode[0]) == 'r') fileMode = string("r"); else return -1; FILE* ofp; ofp = fopen(fileName, fileMode.c_str()); if (! ofp) return -1; *fd = (long)_fileno(ofp); if (*fd < 0) return -1; return 0; } long CloseFD(long fd) { close((int)fd); return 0; } 

After calling GetFD again with the corresponding CloseFD, the entire dll will no longer be able to execute any input / output file. I wrote a tester program and found that I can get GetFD 509 times, but there will be an error 510th time.

Using Process Explorer, the number of pens has not increased.

So, it seems that the dll is reaching the limit for the number of open files; setting _setmaxstdio(2048) increases the time we can call GetFD. Obviously, close () works just fine.

After a bit of searching, I replaced the fopen() call with:

 long GetFD(long* fd, const char* fileName, const char* mode) { *fd = (long)open(fileName, 2); if (*fd < 0) return -1; return 0; } 

Now, repeatedly calls GetFD / CloseFD.

What's going on here?

+4
source share
5 answers

If you open a file with fopen , you need to close it symmetrically with fclose .

A C ++ script should be able to clean / free the internal structures associated with the file.

+17
source

You need to use fclose with files open through fopen or close with files open through open .

+8
source

The standard library that you use has a static array of FILE structures. Since you do not call fclose() , the standard library does not know that the underlying files have been closed, so it does not know that it can reuse the corresponding FILE structures. You will get an error after it has finished writing to the FILE array.

+5
source

fopen opens its own file descriptor, so you need to do fclose(ofp) in your original function to prevent the exhaustion of file descriptors. As a rule, one uses the open, close file descriptor functions OR, buffered fopen, fclose functions.

+3
source

you open the fopen () function of the file, so you need to close the file using fclose (), if you use the open () function and try to call the fclose () function, it will not work

+2
source

Source: https://habr.com/ru/post/1306234/


All Articles