How do I get a list of files in a directory in C++?

后端 未结 13 1396
南旧
南旧 2020-11-28 23:36

How do you get a list of files within a directory so each can be processed?

相关标签:
13条回答
  • 2020-11-28 23:41
    HANDLE WINAPI FindFirstFile(
      __in   LPCTSTR lpFileName,
      __out  LPWIN32_FIND_DATA lpFindFileData
    );
    

    Setup the attributes to only look for directories.

    0 讨论(0)
  • 2020-11-28 23:47

    You have to use operating system calls (e.g. the Win32 API) or a wrapper around them. I tend to use Boost.Filesystem as it is superior interface compared to the mess that is the Win32 API (as well as being cross platform).

    If you are looking to use the Win32 API, Microsoft has a list of functions and examples on msdn.

    0 讨论(0)
  • 2020-11-28 23:48

    After combining a lot of snippets, I finally found a reuseable solution for Windows, that uses ATL Library, which comes with Visual Studio.

    #include <atlstr.h>
    
    void getFiles(CString directory) {
        HANDLE dir;
        WIN32_FIND_DATA file_data;
        CString  file_name, full_file_name;
        if ((dir = FindFirstFile((directory + "/*"), &file_data)) == INVALID_HANDLE_VALUE)
        {
            // Invalid directory
        }
    
        while (FindNextFile(dir, &file_data)) {
            file_name = file_data.cFileName;
            full_file_name = directory + file_name;
            if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
            {
                std::string fileName = full_file_name.GetString();
                // Do stuff with fileName
            }
        }
    }
    

    To access the method, just call:

    getFiles("i:\\Folder1");
    
    0 讨论(0)
  • 2020-11-28 23:49

    But boost::filesystem can do that: http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp

    0 讨论(0)
  • 2020-11-28 23:49

    C++11/Linux version:

    #include <dirent.h>
    
    if (auto dir = opendir("some_dir/")) {
        while (auto f = readdir(dir)) {
            if (!f->d_name || f->d_name[0] == '.')
                continue; // Skip everything that starts with a dot
    
            printf("File: %s\n", f->d_name);
        }
        closedir(dir);
    }
    
    0 讨论(0)
  • 2020-11-28 23:54

    If you're in Windows & using MSVC, the MSDN library has sample code that does this.

    And here's the code from that link:

    #include <windows.h>
    #include <tchar.h> 
    #include <stdio.h>
    #include <strsafe.h>
    
    void ErrorHandler(LPTSTR lpszFunction);
    
    int _tmain(int argc, TCHAR *argv[])
    {
       WIN32_FIND_DATA ffd;
       LARGE_INTEGER filesize;
       TCHAR szDir[MAX_PATH];
       size_t length_of_arg;
       HANDLE hFind = INVALID_HANDLE_VALUE;
       DWORD dwError=0;
    
       // If the directory is not specified as a command-line argument,
       // print usage.
    
       if(argc != 2)
       {
          _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
          return (-1);
       }
    
       // Check that the input path plus 2 is not longer than MAX_PATH.
    
       StringCchLength(argv[1], MAX_PATH, &length_of_arg);
    
       if (length_of_arg > (MAX_PATH - 2))
       {
          _tprintf(TEXT("\nDirectory path is too long.\n"));
          return (-1);
       }
    
       _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);
    
       // Prepare string for use with FindFile functions.  First, copy the
       // string to a buffer, then append '\*' to the directory name.
    
       StringCchCopy(szDir, MAX_PATH, argv[1]);
       StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
    
       // Find the first file in the directory.
    
       hFind = FindFirstFile(szDir, &ffd);
    
       if (INVALID_HANDLE_VALUE == hFind) 
       {
          ErrorHandler(TEXT("FindFirstFile"));
          return dwError;
       } 
    
       // List all the files in the directory with some info about them.
    
       do
       {
          if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
          {
             _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
          }
          else
          {
             filesize.LowPart = ffd.nFileSizeLow;
             filesize.HighPart = ffd.nFileSizeHigh;
             _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
          }
       }
       while (FindNextFile(hFind, &ffd) != 0);
    
       dwError = GetLastError();
       if (dwError != ERROR_NO_MORE_FILES) 
       {
          ErrorHandler(TEXT("FindFirstFile"));
       }
    
       FindClose(hFind);
       return dwError;
    }
    
    
    void ErrorHandler(LPTSTR lpszFunction) 
    { 
        // Retrieve the system error message for the last-error code
    
        LPVOID lpMsgBuf;
        LPVOID lpDisplayBuf;
        DWORD dw = GetLastError(); 
    
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | 
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dw,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0, NULL );
    
        // Display the error message and exit the process
    
        lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
            (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
        StringCchPrintf((LPTSTR)lpDisplayBuf, 
            LocalSize(lpDisplayBuf) / sizeof(TCHAR),
            TEXT("%s failed with error %d: %s"), 
            lpszFunction, dw, lpMsgBuf); 
        MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 
    
        LocalFree(lpMsgBuf);
        LocalFree(lpDisplayBuf);
    }
    
    0 讨论(0)
提交回复
热议问题