0

Is it possible to portably access the maximum number of files that can be simultaneously open within the current process, in C++ (e.g. the result of ulimit -n on unix systems)? I'm writing an application in C++ that potentially requires hundreds of open files, often more than the systems default maximum. Going over the maximum open file limit generally causes difficult to diagnose crashes, especially as most users are not aware of the limit. If I knew the limit at startup, I could potentially warn the user of potential issues, or give a better error message when things go wrong.

Daniel
  • 8,179
  • 6
  • 31
  • 56

1 Answers1

2

In POSIX-compatible systems (which I think includes Windows):

#include <sys/resource.h>

struct rlimit lim;
getrlimit(RLIMIT_NOFILE, &lim);
rlim_t max_files = lim.rlim_cur;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Windows is not a POSIX system – Remy Lebeau Feb 08 '18 at 22:34
  • @RemyLebeau [Wikipedia](https://en.wikipedia.org/wiki/POSIX#POSIX_for_Microsoft_Windows) says "Windows C Runtime Library and Windows Sockets API implement commonly used POSIX API functions for file, time, environment, and socket access,[33] although the support remains largely incomplete and not fully interoperable with POSIX-compliant implementations." – Barmar Feb 08 '18 at 22:38
  • Having a few POSIX-compatible functions does not make it a POSIX system – Remy Lebeau Feb 08 '18 at 22:39
  • Changed my answer to say POSIX-compatible. – Barmar Feb 08 '18 at 22:42
  • Windows itself doesn't have a `getrlimit()` function, so I suppose it would depend on which vendor's C library implementation you are using. – Remy Lebeau Feb 08 '18 at 22:51