Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CString extract file path

Tags:

c++

find

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

like image 383
akif Avatar asked Aug 07 '26 20:08

akif


2 Answers

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);
like image 129
TheUndeadFish Avatar answered Aug 10 '26 08:08

TheUndeadFish


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);
}
like image 44
user2893484 Avatar answered Aug 10 '26 08:08

user2893484



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!