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

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

    Here is a very simple code in C++11 using boost::filesystem library to get file names in a directory (excluding folder names):

    #include 
    #include 
    #include 
    using namespace std;
    using namespace boost::filesystem;
    
    int main()
    {
        path p("D:/AnyFolder");
        for (auto i = directory_iterator(p); i != directory_iterator(); i++)
        {
            if (!is_directory(i->path())) //we eliminate directories
            {
                cout << i->path().filename().string() << endl;
            }
            else
                continue;
        }
    }
    

    Output is like:

    file1.txt
    file2.dat
    

提交回复
热议问题