[英]C++ argv path specifier
在我的編程語言解釋器中,如果調用import
函數,我必須正確處理這些部分。 然后,我需要檢查這樣的文件是否在/libs
文件夾中(與我的可執行文件位於同一位置!),如果不存在,則必須檢查當前腳本的目錄。
從路徑末尾刪除文件的最佳方法是什么,例如:
C:/a/b/c/file.exe
應該變成C:/a/b/c/
argv[0]
但是它是否具有完整路徑或僅是二進制文件的名稱取決於平台以及如何調用進程。 strrchr
查找最后一個斜杠並將其后的字符替換為'\\0'
代碼示例:
// Duplicate the string so as not to trash the original
// You can skip this if you don't mind modifying the original data
// and the originald is writeable (i.e. no literal strings)
char *path = strdup(...);
char *last_slash = strrchr(path, '/');
if (last_slash)
{
#if PRESERVE_LAST_SLASH
*(last_slash + 1) = '\0';
#else
*last_slash = '\0';
#endif
}
如果argv [0]不包含完整路徑,則在Linux(以及其他* nix)上不可移植的方法是在/ proc / self / exe上使用readlink。
如果您的環境在該環境中具有PWD的等效項,則只需在其后附加/ $ argv [0]。
這可能會給您一些意想不到的東西,例如/foo1/foo2/../foo3/,但這沒關系。 這是有效路徑,可以被修改。
從字符串末尾向后掃描第一個'/'
字符。
並非最佳,但效果很好:
int main(int argc, char **argv) {
using namespace std;
char buffer[MAXPATHLEN];
realpath(argv[0], buffer);
string fullpath = buffer;
fullpath = string(fullpath, 0, fullpath.rfind("/"));
cout << fullpath << endl;
}
對於相對路徑,我使用的是realpath(),它是unix / linux特定的。 對於Windows,您可以使用GetModuleFileName(NULL,buffer,MAXPATHLEN),當然分隔符也不相同。
對於Windows(非便攜式),請使用:: GetModuleFileName()和:: PathRemoveFileSpec():
TCHAR sPath[MAX_PATH] = {0};
if(::GetModuleFileName(NULL, sPath, MAX_PATH))
::PathRemoveFileSpec(sPath))
// sPath is the executable path if the module is an exe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.