I am attempting to write a directory list into a char array but getting segmentation faults when attempting to use strcpy or strcat. Is there a better way to go about this?
I am just wanting to modify the following to create a string instead of printing to stdout. I am guessing I am just missing something really simple, but I have not been able to pin it down.
#include <stdio.h>
#include <dirent.h>
int main(void)
{
char returnData[2048];
struct dirent *de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory" );
return 0;
}
// Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
// for readdir()
while ((de = readdir(dr)) != NULL)
printf("%s
", de->d_name); //strcat(returnData, de->d_name); produces segmentation fault here.
closedir(dr);
return 0;
}
See Question&Answers more detail:os