I’ve got a strange problem which I need help with. I’ve made a C++ program that gets some data from a .txt file and writes some data to another .txt file. When I compile and run the program by Xcode, it makes the output file in the same directory as the program file – that’s exactly what I need. But when I close Xcode and run the program just by double–clicking on it, it creates an output file in my Users directory. Is there a way to fix this?
Share
You can use
argv[0]to retrieve the full path of your program.Then, either
chdirto that path, or open the target file with a full path built from the first one.For example:
It is safe to “blindly”
chdirinto whateverdirnamereturns, fordirnamewill return “.” (the current directory) in case of error.Or also:
The above will set
new_bufferto the full pathname of a file calledmyfile.txtin the same directory of the executable. We need two buffers becausedirnamemay return a pointer to static storage, and it would not be safe to append “myfile.txt” directly to the returned string pointer trusting it is a modified version ofpath_buffer.It would be possible to edit
path_buffer, without resorting todirname. This causes portability problems, for the directory separator isn’t necessarily “/”; it and might be “\”.