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

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

    Building on what herohuyongtao posted and a few other posts:

    http://www.cplusplus.com/forum/general/39766/

    What is the expected input type of FindFirstFile?

    How to convert wstring into string?

    This is a Windows solution.

    Since I wanted to pass in std::string and return a vector of strings I had to make a couple conversions.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::vector listFilesInDir(std::string path)
    {
        std::vector names;
        //Convert string to wstring
        std::wstring search_path = std::wstring_convert>().from_bytes(path);
        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)) 
                {
                    //convert from wide char to narrow char array
                    char ch[260];
                    char DefChar = ' ';
                    WideCharToMultiByte(CP_ACP, 0, fd.cFileName, -1, ch, 260, &DefChar, NULL);
                    names.push_back(ch);
                }
            } 
            while (::FindNextFile(hFind, &fd));
            ::FindClose(hFind);
        }
        return names;
    }
    

提交回复
热议问题