fopen()
不需要完整路徑。你可能是正確的,工作目錄不是應用程序所期望的(儘管我不會說它是「錯誤的」,因爲除了從命令行啓動程序(用戶控制它)之外沒有對工作目錄的期望)。
POSIX的方法來改變工作目錄是:
#include <unistd.h>
int chdir(const char *path);
要發現應用程序包的路徑,您使用的Core Foundation的CFBundle API。所以,這樣的事情:
#include <unistd.h>
#include <CoreFoundation/CoreFoundation.h>
...
CFURLRef url = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(url, true, (UInt8*)path, sizeof(path)) ||
chdir(path) != 0)
/* handle error */;
CFRelease(url);
在這裏,我使用的應用程序包(YourApp.app/Contents/Resources)內資源目錄的路徑。如果這不是您的資源文件實際位於的位置,您可以使用其他CFBundle函數之一。
像冠軍一樣工作,並保留與ifdef的X平臺兼容! –