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

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

    C++17 now has a std::filesystem::directory_iterator, which can be used as

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

    Also, std::filesystem::recursive_directory_iterator can iterate the subdirectories as well.

提交回复
热议问题