Source path of CString file

Hey, I am trying to extract the file path, but the problem is I am stuck in an infinite loop, I don’t understand why. Please see 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 on first run, but then in the while loop it returns 2, why can't the function find the rest of the '\' ? So now I'm in an infinite loop: (.

+2


source to share


6 answers


It looks like it Find

contains a character at the position you give when searching. So if you give it the position of the character that matches the search, then it will return the same position.

You probably need to change it to:



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

      

+3


source


your code will never work! When the while loop has finished, the pos call cannot be used. Here's a solution that will work:



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

      

+3


source


CString::Find

always returns the first occurrence of the character you are looking for. So it keeps on finding the first one "\\"

, which is at index 2 infinitely, as you are looking for from 2 which includes"\\"

+1


source


You can fix the code (see pos + 1 answers), but I think it should be used _splitpath_s

for operations like this instead .

+1


source


I can understand your original implementation as the behavior of CString :: Find () seems to have changed over time.

Take a look at the MSDN docs for the MFC implementation shipped with VC6 here and the current implementation here . Pay particular attention to the differences in the description of the second offset parameter.

The solution to your problem, as pointed out above, is to add 1 to the search offset of successive Find () calls. You can also search for single characters (or wchar_ts):

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

      

EDIT:

BTW, have a look at the Path * familly functions exposed by shlwapi.dll declared in shlwapi.h. The PathRemoveFileSpec function is especially interesting .

+1


source


in MFC, for example, to get the folder that includes the executable:

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;

      

+1


source







All Articles