tags:

views:

350

answers:

4

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.

CString 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 :(.

+1  A: 

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 "\\"

Jacob
+2  A: 

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);
TheUndeadFish
+1  A: 

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.

Shay Erlichmen
A: 

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.

Frank Bollack