How can I get the list of files in a directory using C or C++?

前端 未结 27 3166
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  情歌与酒
    2020-11-21 06:14

    One function is enough, you don't need to use any 3rd-party library (for Windows).

    #include 
    
    vector get_all_files_names_within_folder(string folder)
    {
        vector names;
        string search_path = folder + "/*.*";
        WIN32_FIND_DATA fd; 
        HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); 
        if(hFind != INVALID_HANDLE_VALUE) { 
            do { 
                // read all (real) files in current folder
                // , delete '!' read other 2 default folder . and ..
                if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                    names.push_back(fd.cFileName);
                }
            }while(::FindNextFile(hFind, &fd)); 
            ::FindClose(hFind); 
        } 
        return names;
    }
    

    PS: as mentioned by @Sebastian, you could change *.* to *.ext in order to get only the EXT-files (i.e. of a specific type) in that directory.

提交回复
热议问题