Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason fopen() wouldn't work after several hundred opens?

Tags:

c++

fopen

Hey, for this piece of code, the person who wrote the system communicates data between processes using textfiles. I have a loops that looks (for all intents and purposes) like this:

while (true)
{
 //get the most up-to-date info from the other processes
 pFile = fopen(paramsFileName, "r");

 // Do a bunch of stuff with pFile

 Sleep(100);
}

This will work for several hundred times, but for whatever reason it will return NULL after a while, even though it has opened that same file path several hundred times already! I have double checked that the file exists and has data in it when the fopen returns NULL, and have tried to put a delay/retry in there to no effect.

What can you think of that would cause this?

like image 829
Paul Avatar asked Aug 23 '10 16:08

Paul


People also ask

What can cause fopen to fail?

The fopen() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.

What value is returned by fopen () if the file to be opened does not exist?

Opens the file for reading only. If the file cannot be opened fopen() returns NULL.

Can I fopen a file twice?

You can not open a file twice for writing.

What happens when you call fopen?

The fopen() function opens the file that is specified by filename . The mode parameter is a character string specifying the type of access that is requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.


2 Answers

You're hitting the open file / file descriptor limit for your OS. It should run forever if you do fclose(pFile) in your loop.

like image 178
NG. Avatar answered Nov 03 '22 15:11

NG.


You really want to check your return codes. I suspect perror/strerror with the right errno would report that you've exausted your file descriptor limit.

Try something like this and see if you get a good error message.

FILE* f = fopen(filename);
if (NULL == f) {
    fprintf(stderr, 
            "Could not open: %s. %s\n", 
            filename, 
            strerror(errno);
}
like image 5
Paul Rubel Avatar answered Nov 03 '22 14:11

Paul Rubel