How to properly use scandir() in c?

前端 未结 4 869
独厮守ぢ
独厮守ぢ 2021-02-06 10:42

I am trying to store list of files in a char** variable.

scandir() finishes properly but I get a segmentation fault when trying to print the char**.

Here\'s the co

4条回答
  •  梦谈多话
    2021-02-06 11:36

    This is an old question, but since I came upon it and it did not solve my question as effectively as the man page did, I am copying a code snippet from the man page as a new answer for the future.

      #include 
    
       int
       main(void)
       {
           struct dirent **namelist;
           int n;
    
           n = scandir(".", &namelist, NULL, alphasort);
           if (n < 0)
               perror("scandir");
           else {
               while (n--) {
                   printf("%s\n", namelist[n]->d_name);
                   free(namelist[n]);
               }
               free(namelist);
           }
       }
    

提交回复
热议问题