本文由 @lonelyrains 出品,转载请注明出处。
文章链接: http://blog.csdn.net/lonelyrains/article/details/41960455
为此,需要获取执行文件的绝对路径。用到函数_NSGetExecutablePath。这个函数获取的路径是app包里的执行文件的路径,直接在后面加上'/../../../../'到app路径也是不行的,大概是访问权限的问题,会导致fopen失败。
所以先将获取的路径处理一下,得到app路径,再在fopen中调用,经证实是OK的。
代码如下:
// get app path.
#include <mach-o/dyld.h>
char g_path[MAXPATHLEN+1];
- (void)getAppPath
{
uint32_t size = sizeof(g_path);
if (_NSGetExecutablePath(g_path, &size) == 0)
printf("executable path is %s\n", g_path);
else
printf("buffer too small; need size %u\n", size);
// /Users/blade/proj//Output/MacOS/bin/TestTool.app/Contents/MacOS/TestTool
if(strlen(g_path))
{
int end,count = 0;
for(int i = strlen(g_path) - 1; i>0; i--)
{
if(g_path[i] == '/')
{
count++;
}
if(count == 4)
{
end = i;
break;
}
}
if(end > 0)
{
memset(g_path+end,0,strlen(g_path)-end);
}
}
}