简体   繁体   中英

How do I use File I/O pathing correctly in C++ application in OSX?

I have little to none expertise in programming for OSX. I am developing a sprite based 2D game using C++. My code was originally wrote for Visual Studio and is now been ported to OSX.

On the Windows environment all I/Os operations (eg Loading the sprite sheets) are done using relative path, from the current .exe directory. However, on the OSX environment, the compiled program is executed on a different directory and therefore, crashes. When executed from XCode it works perfectly (because it does not change the execution directory).

The Xcode is set as Console application.

My question: Is there any way to set the program so it executes on the correct directory? Since this program is going to be distributed, I'd like to keep the program files as hidden as possible without requiring installation.

thanks in advance

First, its a bad idea to have your program depend on where the executable is to find its files. It is better to pass in a pointer to a configuration file on the command line or something like that, and have the configuration file say where all the data is. This way it is easy for you to install the executable and the data in the most appropriate place on each operating system

However to answer your question, first you find the directory where you exe is, then you change the working directory to that directory. Like this:

char pathbuf[PATH_MAX + 1];
int  bufsize = sizeof(pathbuf);

_NSGetExecutablePath( pathbuf, &bufsize);

chdir( pathbuf );

Error checking was omitted for brevity, but recommended. YOu will need to include:

#include <mach-o/dyld.h>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM