繁体   English   中英

如何检查特定文件夹中是否有文件?

[英]How to check if any file exist in specific folder?

我正在使用CreateProcess复制文件。 如果PC处于离线状态,如果目录不存在,我也可以捕获其他错误。 这是我遇到的问题:如果所有复制成功,则返回0作为错误代码,如果源文件夹中的文件为零,则返回0,因此不进行复制。 我必须检测源文件夹中是否没有文件。 如何在MFC VC ++ 2013中做到这一点?

我花了几个小时尝试不同的解决方案,但是我的知识不足以实现我在Internet上找到的所有内容。 所以我必须要代码,然后我才能理解。 先感谢您。

这是我使用的代码:

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);
}

如果可以使用C ++ 17中引入的<filesystem>头文件中的directory_iterator

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;
}

您可以使用WIN32函数GetFileAttributes(..)来检查文件是否存在:

if (GetFileAttributes("C:\\test.txt") != INVALID_FILE_ATTRIBUTES)
{
    /* C:\test.txt is existing */
}

另一种方法可能只是尝试打开文件(如果成功则再次关闭它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM