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)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With