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:");
CodePudding user response:
if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx"))
This is comparing the whole file name. You only want to compare the file extension:
...
else
{
std::wstring test = findfiledata.cFileName;
auto dot = test.find_last_of(L'.');
if (dot == std::wstring::npos)
continue;
auto ext = test.substr(dot);
if (ext == L".doc" || ext == L".docx")
{
std::wstring path = inputstr L"\\" findfiledata.cFileName;
std::wcout << path << '\n';
//vec.push_back(path) instead of CopyFile!
}
}
Putting CopyFile
inside that recursive function may cause problems. FindNextFile
could see the new copied file, and the function tries to copy it again.
You could instead save the result in a vector of strings, then copy the file once cc
is finished.
void cc(std::wstring inputstr, std::vector<std::wstring> &vec);
...
std::vector<std::wstring> vec;
cc(L"D:", vec);
for (auto& e : vec)
std::wcout << e << '\n';
Also initialize findfiledata
to zero
WIN32_FIND_DATA findfiledata = { 0 };