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

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

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

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 
    
    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");
    

提交回复
热议问题