我正在将Linux C++ 03应用程序移植到Darwin OS X,并具有一些代码来读取/ proc / self / exe中的符号链接(symbolic link),以确定运行可执行文件的目录。
如何计算在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;
}
最佳答案
这是我确定的解决方案:
bool
resolveBinaryLocation(string &binaryDirname)
{
const size_t bufSize = PATH_MAX + 1;
char dirNameBuffer[bufSize];
#ifdef __APPLE__
uint32_t size = bufSize;
if (_NSGetExecutablePath(dirNameBuffer, &size) != 0) {
// Buffer size is too small.
return false;
}
#else // not __APPLE__
// 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 __APPLE__
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;
}
关于c++ - 在Macintosh OS X Mavericks上等效于/proc/self/exe?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22675457/