上文說到,得到執行的正確路徑。有時這個路徑并不規范,所以要進行一番標準化。具體工作:
- //替換為/
- /./替換為/
- ../的處理
近來專門研究了一下,寫了個代碼。其實也不難,主要是處理../時麻煩。
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;
}