C++17 added the
<filesystem> library. Using it doesn't require OS specific libraries to get the current working directory, or change to a different directory such as the OS temp dir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// https://en.cppreference.com/w/cpp/filesystem/current_path
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::cout << "Current working path is: " << fs::current_path() << "\n\n";
// change the current working path to the temp dir
fs::current_path(fs::temp_directory_path());
std::cout << "Current temp path is:\t" << fs::current_path() << '\n';
}
| |
On my Win10 system I get the following output, I can't test for *nix:
Current working path is: "C:\\Programming\\My Projects\\Project1\\Project1"
Current temp path is: "C:\\Users\\Owner\\AppData\\Local\\Temp" |
FYI, the "working directory" is the dir your OS/IDE believes is the directory where the program was launched. When launching within Visual Studio the actual directory where the executable is located can be different.
If I were to run the executable outside of VS I would launch it from one of the sub-folders created during the compile and link process. For x86 (32-bit) non-debug (release) builds the folder(s) would be: "C:\\Programming\\My Projects\\Project1\\Release", x64 (64-bit): "C:\\Programming\\My Projects\\Project1\\x64\\Release".
For debug change "Release" to Debug".
If I copy/move the executable to a different folder the program correctly shows the correct directory where it was launched from.
Long story, short; if C++ has a library to do something you should use the C++ library. Don't use OS specific headers/libraries whenever possible. Better to be OS agnostic if you can be.