如何使用Visual C++获取文件夹中的所有文件名

How can I get Get All Filenames in a Folder using Visual C++?

本文关键字:文件名 文件夹 何使用 Visual C++ 获取      更新时间:2023-10-16

我试过这个代码,但没有得到任何输出。它也不会抛出错误。

#include <windows.h>
int main(int argc, char* argv[])
{
   WIN32_FIND_DATA search_data;
   memset(&search_data, 0, sizeof(WIN32_FIND_DATA));
   HANDLE handle = FindFirstFile("c:\*.txt", &search_data);
while(handle != INVALID_HANDLE_VALUE)
 {
  printf("Found file: %srn", search_data.cFileName);
  if(FindNextFile(handle, &search_data) == FALSE)
    break;
 }
 return 0;
}`
//using boost file system.    
#include <boost/filesystem.hpp>
#include <iostream>
int main()
{
    using namespace boost::filesystem;
    path myPath(L"D:\Article");
    for (auto beg = directory_iterator(myPath); beg != directory_iterator();   ++beg) {
    std::cout << *beg << std::endl;
    }
}

您没有得到任何输出,因为FindFirstFile()失败并且您忽略了错误。始终检查API错误代码。

试试这个。

#include <windows.h>
int main(int argc, char* argv[])
{
     WIN32_FIND_DATA search_data;
     DWORD err;
     memset(&search_data, 0, sizeof(WIN32_FIND_DATA));
     HANDLE handle = FindFirstFile("c:\*.txt", &search_data);
     if (handle == INVALID_HANDLE_VALUE)
     {
         err = GetLastError();
         if (err == ERROR_FILE_NOT_FOUND)
             printf("No files were foundrn");
         else
             printf("Unable to search for files. Error: %urn", err);
     }
     else
     {
         do
         {
             if ((search_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
                 printf("Found file: %srn", search_data.cFileName);
         }
         while (FindNextFile(handle, &search_data));
         err = GetLastError();
         if (err == ERROR_NO_MORE_FILES)
             printf("Donern");
         else
             printf("Unable to search for files. Error: %urn", err);
         FindClose(handle);
     }
     return 0;
}