Gemery

导航

VC通过相对路径获取绝对路径

编程中,有时候会遇到这样的问题,

当运行某个程序:

D:\abc\efg\123.exe时

如果想得到efg目录下的xxx.txt文件的路径,那么可以用".\xxx.txt"或者"xxx.txt"相对于123.exe,  调用:G2XGetFullpath(".\xxx.txt", NULL); 或则G2XGetFullpath("..\efg\xxx.txt", NULL);

如果想得到abc目录下的yyy.txt文件的路径,那么可以用"..\yyy.txt"相对于123.exe, 调用:G2XGetFullpath("..\yyy.txt", NULL);

如果想得到D:目录下的zzz.txt文件的路径,那么可以用"..\..\zzz.txt"相对于123.exe,调用:G2XGetFullpath("..\..\zzz.txt", NULL);

/*
  通过相对路径相对于某个绝对路径,获取全路径
  
lpszRelativePath: 相对路径
  lpszAbsolutePath: 相对的绝对路径,如果为NULL,表明相对于当前模块所在的目录
*/
CString G2XGetFullpath( LPCTSTR lpszRelativePath, LPCTSTR lpszAbsolutePath) { CString strAbsPath;
if (lpszAbsolutePath) { strAbsPath = lpszAbsolutePath; strAbsPath.TrimRight(_T('\\')); strAbsPath.AppendChar(_T('\\')); } else { strAbsPath = G2XGetCurrentDirectory(); // 获取当前模块所在的目录, 该函数很简单,没有写,可自行编写 } strAbsPath.Trim(); if (lpszRelativePath == NULL || *lpszRelativePath == 0) return _T(""); if (*lpszRelativePath == _T('.')) { if (*(lpszRelativePath+1) == _T('\\') ) { //当前目录 strAbsPath += (lpszRelativePath+2); return strAbsPath; } else { G2XUtility::CGxxString<TCHAR> strTmp(lpszRelativePath); int nAt = strTmp.FindString(_T("..\\"), 0); if (nAt != 0) { CString strError; strError.Format(_T("无效的路径 %s"), lpszRelativePath); ERROR_TRACINGT(strError); return _T(""); } else { while(nAt == 0) { strAbsPath.TrimRight(_T('\\')); int nR = strAbsPath.ReverseFind(_T('\\')); if (nR == -1) { CString strError; strError.Format(_T("无效的路径 %s"), lpszRelativePath); ERROR_TRACINGT(strError); return _T(""); } CString tmp = strAbsPath.Left(nR + 1); strAbsPath = tmp; strTmp = strTmp.Mid(nAt + 3); nAt = strTmp.FindString(_T("..\\"), 0); } strAbsPath += strTmp.GetData(); return strAbsPath; } } } else if(*lpszRelativePath == _T('\\')) { strAbsPath.TrimRight(_T('\\')); strAbsPath += lpszRelativePath; return strAbsPath; } else { CString strRe = lpszRelativePath; if (strRe.GetLength() > 2) { if (strRe.GetAt(1) == _T(':')) { return strRe; } } strAbsPath += lpszRelativePath; return strAbsPath; } }

 

posted on 2013-01-07 11:26  Gemery  阅读(3577)  评论(0编辑  收藏  举报