Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of open file in a C++ program

Tags:

c++

file

fopen

Is there a simple way to get the number of files opened by a c++ program.

I would like to do it from my code, ideally in C++.

I found this blog article which is using a loop through all the available file descriptor and testing the result of fstat but I am wondering if there is any simpler way to do that.



Edit

It seems that there are no other solution than keeping a count of the files opened. Thanks to everybody for your help.

Kevin

like image 763
Kevin MOLCARD Avatar asked Jun 13 '13 13:06

Kevin MOLCARD


People also ask

How many file opening modes are there in C?

There are four basic operations that can be performed on a file: Creating a new file. Opening an existing file.

How many files are there in C?

C programming language supports two types of files and they are as follows... Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and symbols is called text file (or) ASCII file.

What opens file in C?

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc.

How does open () work in C?

The open function creates and returns a new file descriptor for the file named by filename . Initially, the file position indicator for the file is at the beginning of the file.


1 Answers

Since the files are FILE *, we could do something like this:

In a headerfile that gets included everywhere:

#define fopen(x, y) debug_fopen(x, y, __FILE__, __LINE__)
#define fclose(x)   debug_fclose(x)

in "debugfile.cpp" (must obviously NOT use the above #define's)

struct FileInfo
{
   FileInfo(const char *nm, const char fl, int ln) :  
      name(nm), file(fl), line(ln) {}

   std::string name;
   const char *file;
   int line;
};

std::map<FILE*, FileInfo> filemap;

FILE *debug_fopen(const char *fname, const char *mode, const char *file, int line)
{
   FILE *f = fopen(fname, mode);
   if (f)
   {
      FileInfo inf(fname, file, line);
      filemap[f] = inf;
   }
}

int debug_fclose(FILE *f)
{
   int res = fclose(f);
   filemap.erase(f);
   return res;
}

// Called at some points. 
void debug_list_openfiles()
{
   for( i : filemap )
   {
       cerr << "File" << (void *) i.first << " opened as " << i.second.name 
            << " at " <<  i.second.file << ":" << i.second.line << endl;
   }
}

(I haven't compiled this code, and it's meant to show the concept, it may have minor bugs, but I think the concept would hold - as long as your code, and not some third party library is leaking)

like image 93
Mats Petersson Avatar answered Oct 17 '22 19:10

Mats Petersson