Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

First change:

 char returnData[2048]; 

to

 char returnData[2048] = { '' };

As already mentioned in the comments, you should initialize your Array with Zeros/NUL-Terminator, so the call to strcat is defined as strcat replaces the '' with the src parameter.

And as some compilers complain use strncat or similar instead of strcat. Also don't forget, that you also need to append ' ' to get the same output as with your printf.

You could either calculate the length beforehand resulting in two loops or resize the buffer dynamically.

BTW: Why do you want to store it in a single string?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...