开发者

CString extract file path

Hey I'm trying to extract the file path but the problem is that I'm stuck in an infinite loop don't understand why. Please have a look at my code.

CS开发者_运维知识库tring myString(_T("C:\\Documents and Settings\\admin\\Desktop\\Elite\\Elite\\IvrEngine\\dxxxB1C1.log"));

int pos = myString.Find(_T("\\"));

while (pos != -1)
{
    pos = myString.Find(_T("\\"), pos); // it keeps returning 2
}

CString folderPath = myString.Mid(pos);

Now the problem is that, Find() returns 2 the first time I run, but then in the while loop it keeps returning 2, why is the function unable to find the rest '\' ? So now I'm in an infinite loop :(.


It sounds like Find includes the character at the position you give it when searching. So if you give it the position of a character that matches the search, then it will return that same position.

You probably need to change it to:

pos = myString.Find(_T("\\"), pos + 1);


your code will never work! When the while loop finished, the contend of pos can not be used. Here is a solution which will work:

CString folderPath;
int pos = myString.ReverseFind('\\');
if (pos != -1)
{
    folderPath = myString.Left(pos);
}


You can fix the code (see the pos + 1 answers) but I think that you should use _splitpath_s instead which was intended for this kind of operations.


CString::Find always returns the first occurence of the character you're searching for. So it keeps finding the the first "\\" which is at index 2 infinitely since you're searching from 2 which includes that "\\"


I can understand your initial implementation, as the behaviour of CString::Find() seem to have changed over time.

Take a look at the MSDN docs for MFC implementation shipped with VC6 here and at the current implementation here. Especially look at the differences of the description of the 2nd offset parameter.

The solution to your problem is, as already stated above, to add 1 to the search offset of the successive Find() calls. You can also search for single chars (or wchar_ts) like that:

myString.Find(_T('\\'), pos+1);

EDIT:

BTW, take a look at the Path* familly of functions exposed by the shlwapi.dll, declared in shlwapi.h. Especially the PathRemoveFileSpec function might be of interest to you.


in MFC, example to get folder which including executable file:

char ownPth[MAX_PATH]; 

// Will contain exe path
HMODULE hModule = GetModuleHandle(NULL);
if(NULL == hModule){
    return __LINE__;
}

// When passing NULL to GetModuleHandle, it returns handle of exe itself
GetModuleFileName(hModule,ownPth, (sizeof(ownPth))); 
modulePath = (LPCSTR)ownPth;
modulePath = modulePath.Left(modulePath.ReverseFind(_T('\\')));

return 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜