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

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

    System call it!

    system( "dir /b /s /a-d * > file_names.txt" );
    

    Then just read the file.

    EDIT: This answer should be considered a hack, but it really does work (albeit in a platform specific way) if you don't have access to more elegant solutions.

    0 讨论(0)
  • 2020-11-21 06:31

    you can get all direct of files in your root directory by using std::experimental:: filesystem::directory_iterator(). Then, read the name of these pathfiles.

    #include <iostream>
    #include <filesystem>
    #include <string>
    #include <direct.h>
    using namespace std;
    namespace fs = std::experimental::filesystem;
    void ShowListFile(string path)
    {
    for(auto &p: fs::directory_iterator(path))  /*get directory */
         cout<<p.path().filename()<<endl;   // get file name
    }
    
    int main() {
    
    ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
    getchar();
    return 0;
    }
    
    0 讨论(0)
  • 2020-11-21 06:33

    This implementation realizes your purpose, dynamically filling an array of strings with the content of the specified directory.

    int exploreDirectory(const char *dirpath, char ***list, int *numItems) {
        struct dirent **direntList;
        int i;
        errno = 0;
    
        if ((*numItems = scandir(dirpath, &direntList, NULL, alphasort)) == -1)
            return errno;
    
        if (!((*list) = malloc(sizeof(char *) * (*numItems)))) {
            fprintf(stderr, "Error in list allocation for file list: dirpath=%s.\n", dirpath);
            exit(EXIT_FAILURE);
        }
    
        for (i = 0; i < *numItems; i++) {
            (*list)[i] = stringDuplication(direntList[i]->d_name);
        }
    
        for (i = 0; i < *numItems; i++) {
            free(direntList[i]);
        }
    
        free(direntList);
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题