Determine the number of open files in your program (C/C++)
The code below will display the number of files open by the running process. It does this by getting the maximum file descriptor number and then iterating through each possible fd trying to do an 'fstat' on it. If errno returns anything other than EBADF 'file descriptor is bad' it increments a count. It is fairly portable, tested and working on Linux & Solaris. [cpp] /* * ofiles.c - Displays the number of open files for its own process * Copyright (C) 2005 Michael Cutler * / #include #include #include #include #include #include #include extern int errno; int main ( int argc, char* argv, char** env ) { int i = 0; int fd_counter = 0; int max_fd_number = 0; struct stat stats; struct rlimit rlimits; max_fd_number = getdtablesize(); getrlimit(RLIMIT_NOFILE, &rlimits); printf( "max_fd_number: %d\n", max_fd_number ); printf( " rlim_cur: %d\n", rlimits.rlim_cur ); printf( " rlim_max: %d\n", rlimits.rlim_max ); for ( i = 0; i <= max_fd_number; i++ ) { fstat(i, &stats); if ( errno != EBADF ) { fd_counter++; } } printf( " open files: %d\n", fd_counter ); return 0; } [/cpp] Example: ``` [mcutler@rasco ~]$ gcc -o ofiles ofiles.c [mcutler@rasco ~]$ ./ofiles max_fd_number: 1024 rlim_cur: 1024 rlim_max: 1024 open files: 3 [mcutler@rasco ~]$ ```
The Cutler.sg Newsletter
Weekly notes on AI, engineering leadership, and building in Singapore. No fluff.
Everyone Can Have a Personal Health Adviser Now
Personalized medicine used to mean being rich enough to afford a doctor who knew your name. Last week I built a version of it on my laptop, for free, from a file I'd been ignoring for seven years — and the real unlock is that I can re-run it forever.
Protect the Juniors: Cognitive Debt and the Stack Overflow Collapse
AI is making junior output look senior-level while preventing junior skill from forming — and the Stack Overflow collapse just removed the ambient learning layer that used to catch the deficit. Three interventions that work.
AI as the Great Equaliser: Neurodiversity, Disclosure, and the Tools That Change Everything
For neurodivergent professionals, AI isn't just a productivity tool — it's the first accommodation you can access privately, without disclosure, without stigma, and without asking anyone's permission.