我正在将一个Linux C ++ 03应用程序移植到Darwin OS X,并且有一些代码读取/ proc / self / exe处的符号链接以确定可执行文件运行所在的目录。
如何在C ++中计算在Macintosh Darwin OS X Mavericks上运行的当前可执行文件的目录?
以下是我在Linux上运行的现有代码:
bool
resolveBinaryLocation(string &binaryDirname)
{
// Read the symbolic link '/proc/self/exe'.
const char *linkName = "/proc/self/exe";
const size_t bufSize = PATH_MAX + 1;
char dirNameBuffer[bufSize];
const int ret = int(readlink(linkName, dirNameBuffer, bufSize - 1));
if (ret == -1) {
// Permission denied (We must be inetd with this app run as other than root).
return false;
}
dirNameBuffer[ret] = 0; // Terminate the string with a NULL character.
binaryDirname = dirNameBuffer;
// Erase the name of the executable:
string::size_type last = binaryDirname.size() - 1;
string::size_type idx = binaryDirname.rfind(DSI_PATH_CHAR, last);
// Add one to keep the trailing directory separator.
binaryDirname.erase(idx + 1);
return true;
}
答案 0 :(得分:2)
以下是我作为解决方案所确定的内容:
bool
resolveBinaryLocation(string &binaryDirname)
{
const size_t bufSize = PATH_MAX + 1;
char dirNameBuffer[bufSize];
#ifdef ARCH_darwin_14_i86
uint32_t size = bufSize;
if (_NSGetExecutablePath(dirNameBuffer, &size) != 0) {
// Buffer size is too small.
return false;
}
#else // not ARCH_darwin_14_i86
// Read the symbolic link '/proc/self/exe'.
const char *linkName = "/proc/self/exe";
const int ret = int(readlink(linkName, dirNameBuffer, bufSize - 1));
if (ret == -1) {
// Permission denied (We must be inetd with this app run as other than root).
return false;
}
dirNameBuffer[ret] = 0; // Terminate the string with a NULL character.
#endif // else not ARCH_darwin_14_i86
binaryDirname = dirNameBuffer;
// Erase the name of the executable:
string::size_type last = binaryDirname.size() - 1;
string::size_type idx = binaryDirname.rfind(DSI_PATH_CHAR, last);
// Add one to keep the trailing directory separator.
binaryDirname.erase(idx + 1);
return true;
}