簡體   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