我试图将目录列表写入字符数组,但在尝试使用 strcpy 或 strcat 时出现段错误。有更好的方法来解决这个问题吗?
我只是想修改以下内容来创建一个字符串,而不是打印到stdout。我猜我只是错过了一些非常简单的东西,但我无法确定它。
#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\n", de->d_name); //strcat(returnData, de->d_name); produces segmentation fault here.
closedir(dr);
return 0;
}
最佳答案
第一个变化:
char returnData[2048];
到
char returnData[2048] = { '\0' };
正如评论中已经提到的,您应该使用 Zeros/NUL-Terminator 初始化数组,因此对 strcat
的调用定义为 strcat
将 '\0'
替换为 src
参数。
正如一些编译器提示使用 strncat
或类似的而不是 strcat
。
另外不要忘记,您还需要附加 '\n'
才能获得与 printf
相同的输出。
您可以预先计算长度,从而产生两个循环 或动态调整缓冲区大小。
顺便说一句:为什么要将它存储在单个字符串中?
关于C 将 readdir 写入 char 数组变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804567/