[英]Copy all files .doc or .docx in folder and subfolder into another folder
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. 以下是我所做的,它似乎不起作用:
誰能告訴我如何正確地做到這一點?
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);
}
當我調用 function 時,此處的inputstr
是我想要搜索的驅動器,例如cc(L"D:");
if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx"))
這是比較整個文件名。 您只想比較文件擴展名:
...
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!
}
}
將CopyFile
放入該遞歸 function 可能會導致問題。 FindNextFile
可以看到新復制的文件,並且 function 嘗試再次復制它。
您可以改為將結果保存在字符串向量中,然后在cc
完成后復制文件。
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';
findfiledata
初始化為零
WIN32_FIND_DATA findfiledata = { 0 };
您必須使用wcsstr
或std::wstring::find
而不是wcscmp
,因為您想在FileSearch
中搜索字符串.doc
,而不是將FileSearch
與字符串.doc
進行比較。 我重寫了你的else
分支:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.