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

前端 未结 27 3165
情书的邮戳
情书的邮戳 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: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;
    }
    

提交回复
热议问题