Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use scandir() in c?

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 code:

int main()
{
    char** fileList;
    int noOfFiles;
    char* path = ".";
    makeList(&fileList, &noOfFiles, path); 
    return 0;
}

void makeList(char ***fileList, int* noOfFiles, char* path){
    struct dirent **fileListTemp;
    *noOfFiles = scandir(path, &fileListTemp, NULL, alphasort);
    int i;
    fileList = (char***)malloc(sizeof(char***));
    *fileList = (char**)malloc(*noOfFiles * sizeof(char*));
    printf("total: %d files\n",*noOfFiles);
    for(i = 0; i < *noOfFiles; i++){
        *fileList[i] = (char*)malloc(strlen(fileListTemp[i] -> d_name) *sizeof(char));
        strcpy(*fileList[i], fileListTemp[i] -> d_name);
        printf("%s\n",*fileList[i]);
    }
    return;
}

This gives a segmentation fault after printing 2 file names.

output:

total: 27 files.

..

.j.v

Segmentation fault (core dumped)

like image 748
kBisla Avatar asked Aug 23 '13 12:08

kBisla


1 Answers

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 <dirent.h>

   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);
       }
   }
like image 71
merlin2011 Avatar answered Oct 07 '22 16:10

merlin2011