c++ - 如何检查特定文件夹中是否存在任何文件?
问题描述
我CreateProcess
用来复制文件。我也可以捕捉到不同的错误,如果 PC 离线,如果目录不存在。这是我遇到的问题:如果所有复制都成功,它返回 0 作为错误代码,如果源文件夹中有零个文件,则返回 0,因此不进行复制。我必须检测源文件夹中是否没有文件。如何在 MFC VC++ 2013 中做到这一点?
我花了几个小时尝试不同的解决方案,但我的知识还不足以实现我在互联网上找到的所有内容。所以我必须要代码,然后我就明白了。先感谢您。
这是我使用的代码:
temp_dest = _T("/min /c xcopy \"D:\\Test\\*.*\" \"") + m_destination + _T("\" /Y /E /Q");
LPTSTR temp_dest2 = (LPTSTR)(LPCTSTR)temp_dest;
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
memset(&sinfo, 0, sizeof(STARTUPINFO));
memset(&pinfo, 0, sizeof(PROCESS_INFORMATION));
sinfo.dwFlags = STARTF_USESHOWWINDOW;
sinfo.wShowWindow = SW_HIDE;
BOOL bSucess = CreateProcess(L"C:\\Windows\\System32\\cmd.exe", temp_dest2, NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &sinfo, &pinfo);
DWORD dwCode;
TerminateProcess(pinfo.hProcess, 2);
GetExitCodeProcess(pinfo.hProcess, &dwCode);
TCHAR msg2[100];
StringCbPrintf(msg2, 100, TEXT("%X"), dwCode);
MessageBox(msg2, (LPCWSTR)L"DWCode 2", MB_OK | MB_ICONERROR);
if (dwCode == 4)
{
MessageBox((LPCWSTR)L"DW 4", (LPCWSTR)L"Path not found", MB_OK | MB_ICONERROR);
}
if (dwCode == 2)
{
MessageBox((LPCWSTR)L"DW 4", (LPCWSTR)L"PC Offline", MB_OK | MB_ICONERROR);
}
解决方案
如果可以directory_iterator
从<filesystem>
C++17 中引入的头文件中使用:
bool IsEmptyDirectory( const wchar_t* dir )
{
return std::filesystem::directory_iterator( std::filesystem::path( dir ) )
== std::filesystem::directory_iterator();
}
可能需要std::experimental::filesystem
代替std::filesystem
.
我试图将它移植到 VC 2013,但char
似乎只有版本可以编译
bool IsEmptyDirectory( const char* dir )
{
return std::tr2::sys::directory_iterator( std::tr2::sys::path( dir ) )
== std::tr2::sys::directory_iterator();
}
如果您想(或必须)使用 WinAPI:
bool IsEmptyDirectory( const wchar_t* dir )
{
wstring mask( dir);
mask += L"\\*";
WIN32_FIND_DATA data;
HANDLE find_handle = FindFirstFile( mask.c_str(), &data );
if ( find_handle == INVALID_HANDLE_VALUE )
{
// Probably there is no directory with given path.
// Pretend that it is empty.
return true;
}
bool empty = true;
do
{
// Any entry but . and .. means non empty folder.
if ( wcscmp( data.cFileName, L"." ) != 0 && wcscmp( data.cFileName, L".." ) != 0 )
empty = false;
} while ( empty && FindNextFile( find_handle, &data ) );
FindClose( find_handle );
return empty;
}
推荐阅读
- wcsession - WCSession 检测手表关机。HKHealthStore startWatchApp 挂起
- javascript - 从javascript将mathjax方程插入innerHTML
- c# - 用户登录时如何显示打字指示器
- python - 使用 pydantic_model_creator 创建 pydantic 模型时从 m2m 关系中排除嵌套对象的字段?
- css - 如何在 Dulst 中为卡片添加新的主要属性?
- tcp - 从以太网连接的控制器检索数据时出现问题
- python - 如何在一个脚本中使用 enchant 和 requests.future
- java - 分区方法中退出循环的问题
- javascript - 无法获取旧(以前)购物车的价值
- winapi - 访问物理内存地址