std::fstream and OSX - Why can I not load a file with my raw executable?
I have a C++ project in XCode which uses std::fstream to work with a default text file.
I haven't specified a relative path so I expect that the file will need to be emplaced in the same directory as the executable (As in Windows). This would be my preferred method for now also.
The tricky part is that When I run the project from Xcode, I get the behaviour I expect - the text file is loaded and read. However if I run the executable from finder, I get nothing (Good Day Sir!).
This is the directory pointed to by Xcode under "Products" which takes me to the executable.
Has anyone experienced this behaviour before or know why this might be happening?
Solution 1:
Your executable is looking in the current working directory
(CWD
).
-
When run from Xcode, Xcode actively changes the current working directory to where your executable has been built.
-
When run from the Finder on macOS, the current working directory will not be the directory of your executable. Thus the executable can not find the text file.
Use the getcwd
or std::filesystem::current_path
function to determine the current working directory from within your executable. See Get path of executable for ways to get your executable's path at runtime.