liv2hak
liv2hak

Reputation: 14970

fopen in C(Linux) returns "Too many open files"

static char filename[128] = "trace.txt";

g_file = fopen(filename, "w");
if(NULL == g_file)
{
       printf("Cannot open file %s.error %s\n",filename,strerror(errno));
       exit(1);
}

I am trying to open a empty text file named trace.txt in write mode (in my working directory.) The program is creating an empty file trace.txt in my directory.but the check (NULL == g_file) is returning true and it is returning error code 24 (Too many open files.).Any idea why this is.This is the first file I am opening in my program.

Surprisingly the code is creating an empty file in my working directory by the name specified.However the check for null file pointer is succeeding for some reason.? :(

Upvotes: 2

Views: 17280

Answers (4)

chakra t
chakra t

Reputation: 37

Correct, I faced same error message and found that I was trying to close the file in a function but not where it was opened. So I then closed in the function where it was opened, later everything went fine.

Upvotes: 1

ugoren
ugoren

Reputation: 16441

You probably have a file descriptor leak.
If your code keeps opening files, never closing them, you will reach the limit sooner or later, and then fopen will fail.

You can check this by printing the file descriptor numbers you get whenever opening a file. If they keep growing, you have a leak.

Upvotes: 11

David M. Syzdek
David M. Syzdek

Reputation: 15788

It is most likely due to your system reaching its maximum allowed open file handles.

You can easily test this by running the following:

$ dd if=/dev/urandom of=test.dat bs=16 count=1

If you are out of file handles, this should provide the same or similar error.

You can trouble shoot this using some of the following commands:

To see the maximum allowed open files:

$ cat /proc/sys/fs/file-max

To see the which files are currently open (remember this includes device files, sockets, etc):

$ lsof

You can also use lsof to get a count of open files:

$ lsof | wc -l

Upvotes: 4

LeigerGaming
LeigerGaming

Reputation: 508

This looks like a similar issue to what you're having, but I'm not entirely sure if it will help you solve the problem. Might be worth a look:

Problem with writing to file in C

Upvotes: 1

Related Questions