Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

C writing readdir to char array variable?

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...