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: (.
source to share
You can fix the code (see pos + 1 answers), but I think it should be used _splitpath_s
for operations like this instead .
source to share
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 .
source to share
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;
source to share