2

Currently, when I want to get the user's home directory in C++, I do:

#include <pwd.h>

const char* get_home_directory() {
    struct passwd *pw = getpwuid(getuid());
    return (pw == nullptr ? nullptr : pw->pw_dir);
}

but this relies on getpwuid, which is a POSIX / BSD library function; and it's C rather than C++. Is there a platform-independent, hopefuly more C++'ish way to do the same?

Note: A commonly-used out-of-standard library, even non-Boost, could also work. It would have to support a wide range of platforms though.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 5
    There isn't one. Nothing in the C++ standard says anything about home directories. –  Mar 24 '17 at 22:43
  • @NeilButterworth: I was worried that might be the case. I thought maybe the filesystem library had something like this up its sleeve... also, see my edit. – einpoklum Mar 24 '17 at 22:46
  • Use `cmake` and there you have all the freedom. Passing paths as `defines` or generating dynamically headers - everything possible. – Armen Avetisyan Mar 24 '17 at 22:50
  • AFAIK boost filesystem doesn't support it either. But it's not hard to write portable code for _specific_ operating systems. –  Mar 24 '17 at 22:50
  • @ArmenAvetisyan: That's a fair suggestion I suppose. Although I wish I didn't have to do that. – einpoklum Mar 24 '17 at 22:52
  • There are some platforms, such as smaller embedded systems, that don't have file systems (or home directories). Thus home directories are not in the standard. – Thomas Matthews Mar 24 '17 at 23:06
  • @NeilButterworth: The C++ standard doesn't even say anything about *directories* (yet). – Kerrek SB Mar 24 '17 at 23:13
  • @ThomasMatthews: That's what `nullopt` or `nullptr` are for... – einpoklum Mar 24 '17 at 23:15
  • @KerrekSB: C++17 will, though. – einpoklum Mar 24 '17 at 23:16

0 Answers0