I am new to C++ and winapi, currently working on a project to create a winapi application with a function to copy all files .doc and .docx in one drive to another folder.
Below is what I have done and it doesn’t seem to work:
Can anyone show me how to do this properly ?
void cc(wstring inputstr) {
TCHAR sizeDir[MAX_PATH];
wstring search = inputstr + TEXT("\\*");
wcscpy_s(sizeDir, MAX_PATH, search.c_str());
WIN32_FIND_DATA findfiledata;
HANDLE Find = FindFirstFile(sizeDir, &findfiledata);
do {
if (findfiledata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (!wcscmp(findfiledata.cFileName, TEXT(".")) || !wcscmp(findfiledata.cFileName, TEXT(".."))) continue;
//checking folder or file
wstring dirfolder = inputstr + TEXT("\\") + findfiledata.cFileName;
cc(dirfolder);
}
else {
wstring FileSearch = findfiledata.cFileName;
//.doc or docx
if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx")) {
TCHAR src[256] = L"D:\\test\\";
wstring dirsrc = inputstr + TEXT("\\") + findfiledata.cFileName;
_tprintf(TEXT(" %s \n"), dirsrc.c_str());
wcscat_s(src, findfiledata.cFileName);
CopyFile(dirsrc.c_str(), src, TRUE);
}
}
} while (FindNextFile(Find, &findfiledata) != 0);
FindClose(Find);
}
The inputstr here when i call the function is the drive that i want to search like cc(L"D:");
>Solution :
You must use wcsstr or std::wstring::find instead of wcscmp because you want to search string .doc inside FileSearch, not comparing FileSearch with string .doc. I re-write your else branch:
else {
wstring FileSearch = findfiledata.cFileName;
std::transform(FileSearch.begin(), FileSearch.end(), FileSearch.begin(), ::towlower);
//.doc or docx
if (wcsstr(FileSearch.c_str(), L".doc") || wcsstr(FileSearch.c_str(), L".docx"))
{
TCHAR src[256] = L"D:\\test\\";
wstring dirsrc = inputstr + TEXT("\\") + findfiledata.cFileName;
wprintf_s(TEXT(" %s \n"), dirsrc.c_str());
wcscat_s(src, findfiledata.cFileName);
CopyFile(dirsrc.c_str(), src, TRUE);
}
}