Why is std::filesystem::current_path() not able to get current path? [closed]

4 weeks ago 14
ARTICLE AD BOX

You can check /proc/self/cwd manually on Linux, but note it may show something like path (deleted) when the directory is gone. Why not handle the error:

#include <filesystem> #include <iostream> int main() { std::error_code ec; auto p = std::filesystem::current_path(ec); if (ec) { std::cerr << "Failed to get current path: " << ec.message() << "\n"; // Optional: default to "/" or another known directory // std::filesystem::current_path("/"); } else { std::cout << p << "\n"; } }

If you run via Run and Debug (not CMake Tools’ custom commands), define the launch config and set cwd:

{ "version": "0.2.0", "configurations": [ { "name": "My App (Debug)", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/myapp", // adjust your target name "args": [], "cwd": "${workspaceFolder}/build", "MIMode": "gdb", "miDebuggerPath": "/usr/bin/gdb", "preLaunchTask": "build-myapp" }, { "name": "My App (Run Without Debugging)", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/myapp", "args": [], "cwd": "${workspaceFolder}/build", "MIMode": "gdb", "miDebuggerPath": "/usr/bin/gdb" } ] }

Or CMake Tools provides settings to influence its run/debug behavior. Add this to your workspace settings. If your extension version doesn’t support cmake.runConfig, you can define a CMake custom target that runs your program and sets the working directory via CMake, then select that target for “Run”.

{ "cmake.buildDirectory": "${workspaceFolder}/build", "cmake.debugConfig": { "cwd": "${workspaceFolder}/build" }, "cmake.runConfig": { "cwd": "${workspaceFolder}/build" } }

Or please define a custom target in CMakeLists.txt that runs from the desired directory:

add_executable(myapp src/main.cpp) add_custom_target(run_myapp COMMAND ${CMAKE_COMMAND} -E chdir $<TARGET_FILE_DIR:myapp> $<TARGET_FILE:myapp> DEPENDS myapp COMMENT "Running myapp from its build directory" )

Then choose CMake: Run Without Debugging on the run_myapp target. The cmake -E chdir guarantees a valid cwd.

Kindly note that please dont rely on argv[0]. Its not the working directory rather its the path used to locate the executable (which can be relative, symlinked, or different from the cwd).

Read Entire Article