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

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

    Why not use glob()?

    #include <glob.h>
    
    glob_t glob_result;
    glob("/your_directory/*",GLOB_TILDE,NULL,&glob_result);
    for(unsigned int i=0; i<glob_result.gl_pathc; ++i){
      cout << glob_result.gl_pathv[i] << endl;
    }
    
    0 讨论(0)
  • 2020-11-21 06:21

    I think, below snippet can be used to list all the files.

    #include <stdio.h>
    #include <dirent.h>
    #include <sys/types.h>
    
    static void list_dir(const char *path)
    {
        struct dirent *entry;
        DIR *dir = opendir(path);
        if (dir == NULL) {
            return;
        }
    
        while ((entry = readdir(dir)) != NULL) {
            printf("%s\n",entry->d_name);
        }
    
        closedir(dir);
    }
    

    Following is the structure of the struct dirent

    struct dirent {
        ino_t d_ino; /* inode number */
        off_t d_off; /* offset to the next dirent */
        unsigned short d_reclen; /* length of this record */
        unsigned char d_type; /* type of file */
        char d_name[256]; /* filename */
    };
    
    0 讨论(0)
  • I hope this code help you.

    #include <windows.h>
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    string wchar_t2string(const wchar_t *wchar)
    {
        string str = "";
        int index = 0;
        while(wchar[index] != 0)
        {
            str += (char)wchar[index];
            ++index;
        }
        return str;
    }
    
    wchar_t *string2wchar_t(const string &str)
    {
        wchar_t wchar[260];
        int index = 0;
        while(index < str.size())
        {
            wchar[index] = (wchar_t)str[index];
            ++index;
        }
        wchar[index] = 0;
        return wchar;
    }
    
    vector<string> listFilesInDirectory(string directoryName)
    {
        WIN32_FIND_DATA FindFileData;
        wchar_t * FileName = string2wchar_t(directoryName);
        HANDLE hFind = FindFirstFile(FileName, &FindFileData);
    
        vector<string> listFileNames;
        listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
    
        while (FindNextFile(hFind, &FindFileData))
            listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
    
        return listFileNames;
    }
    
    void main()
    {
        vector<string> listFiles;
        listFiles = listFilesInDirectory("C:\\*.txt");
        for each (string str in listFiles)
            cout << str << endl;
    }
    
    0 讨论(0)
  • 2020-11-21 06:22

    I recommend using glob with this reusable wrapper. It generates a vector<string> corresponding to file paths that fit the glob pattern:

    #include <glob.h>
    #include <vector>
    using std::vector;
    
    vector<string> globVector(const string& pattern){
        glob_t glob_result;
        glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
        vector<string> files;
        for(unsigned int i=0;i<glob_result.gl_pathc;++i){
            files.push_back(string(glob_result.gl_pathv[i]));
        }
        globfree(&glob_result);
        return files;
    }
    

    Which can then be called with a normal system wildcard pattern such as:

    vector<string> files = globVector("./*");
    
    0 讨论(0)
  • 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 <string>
    #include <iostream>
    #include <boost/filesystem.hpp>
    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
    
    0 讨论(0)
  • 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 <iostream>
    #include <filesystem>
    #include <string>
    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.

    0 讨论(0)
提交回复
热议问题