上文说到,得到执行的正确路径。有时这个路径并不规范,所以要进行一番标准化。具体工作:
- //替换为/
- /./替换为/
- ../的处理
近来专门研究了一下,写了个代码。其实也不难,主要是处理../时麻烦。
char* format_to_exe_path(char* pPath) {char pFull[MAX_PATH_SIZE] = {0};if (pPath[0] == '/') {strcpy(pFull, pPath);}else {sprintf(pFull, "%s/%s", g_caExePath, pPath);}char* pFind;//简化,最好是从右向左,能节省一点运算量。char* REPLACES[] = {"//", "/./"};for (int i=0; i<2; i++) {char *pItem = REPLACES[i];//非开头情形,./一定以这种情形出现。while ((pFind = strstr(pFull, pItem)) != NULL) {int nFount = strlen(pFind);pFull[strlen(pFull)-nFount] = 0;sprintf(pFull, "%s/%s", pFull, pFind+strlen(pItem));pFind[nFount] = 0;}}char pLeft[MAX_PATH_SIZE];char pRight[MAX_PATH_SIZE];while ((pFind =strstr(pFull, "../")) != NULL) {memset(pLeft, 0, MAX_PATH_SIZE);int iLeft = strlen(pFull) - strlen(pFind) - 1;if (iLeft > 0) {strncpy(pLeft, pFull, iLeft);strrchr(pLeft, '/')[0] = 0;}ZLOG_ERROR("pLeft=%s", pLeft);memset(pRight, 0, MAX_PATH_SIZE);strcpy(pRight, pFind+3);memset(pFull, 0, MAX_PATH_SIZE);sprintf(pFull, "%s/%s", pLeft, pRight);}strcpy(pPath, pFull);pPath[strlen(pFull)] = 0;return pPath;
}