Is this the correct way to get an "user" directory

Jan 24, 2022 at 8:54pm
I'm still new at VC++ and wondering if this is the best way to get the current user directory in windows?

1
2
3
4
5
6
7
8
  char* userpath = nullptr;
  size_t sz = 0;
  std::string fixedpath = "/Jottacloud/Visual Studio/TilePOC/Galaga.PNG";
  if (_dupenv_s(&userpath, &sz, "USERPROFILE") == 0 && userpath != nullptr) 
  {
    sprTile = std::make_unique<olc::Sprite>(userpath + fixedpath);
    free(userpath);  
  }


I know the code is working, but just wondering if it is an effecient/correct way to do it.

Regards
Allan
Last edited on Jan 24, 2022 at 8:56pm
Jan 24, 2022 at 10:36pm
<filesystem> has the current path without having to resort to C.
https://en.cppreference.com/w/cpp/filesystem/current_path
Jan 25, 2022 at 8:29pm
Thank you. Might be able to use that in another project, but can't for this one.

I have to get the windows User profile directory as "base" and add the relative path from there, because i move the project between different machines during development.

That's why i grab the USERPROFILE enviroment variable, and my question was if the way i do that, is the "correct" way. Your answer tells med, that i have too much "C baggage" with me. ;)

But i can't seem to find any safe C++ way of getting the env variable. So my question is actually if there is a better way to grab that USERPROFILE env. var than resorting to C ;)

Regards
Allan
Jan 25, 2022 at 11:47pm
Ah, I see.
Most of the windows code is still using C strings, unfortunately.
there is
GetEnvironmentVariable
getenv
and probably others.

I would thing
string s{genenv("variable")};
might work. string is overloaded to construct from C strings, so after the one call its back to OOP.
My main goal here would be getting rid of any hands on dynamic memory, even the smart pointer. It feels excessive if it can be avoided.
Last edited on Jan 25, 2022 at 11:48pm
Jan 26, 2022 at 12:02am
I would think
string s{getenv("variable")};
might work.

Would be fine, as long as you check to make sure getenv doesn't return a null pointer first.
Jan 26, 2022 at 7:06am
So my original piece of code is still an ok way to do it in C++? (I am checking if a nullptr is returned, and i changed from getenv to _dupenv_s as my compiler suggested.)

Was just hoping there were a nicer way as the original code is a bit "clunky". ;)

Regards
Allan
Last edited on Jan 26, 2022 at 7:07am
Jan 26, 2022 at 9:42am
Topic archived. No new replies allowed.