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

前端 未结 27 3175
情书的邮戳
情书的邮戳 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:25

    I tried to follow the example given in both answers and it might be worth noting that it appears as though std::filesystem::directory_entry has been changed to not have an overload of the << operator. Instead of std::cout << p << std::endl; I had to use the following to be able to compile and get it working:

    #include 
    #include 
    #include 
    namespace fs = std::filesystem;
    
    int main() {
        std::string path = "/path/to/directory";
        for(const auto& p : fs::directory_iterator(path))
            std::cout << p.path() << std::endl;
    }
    

    trying to pass p on its own to std::cout << resulted in a missing overload error.

提交回复
热议问题