C 将 readdir 写入 char 数组变量?

标签 c

我试图将目录列表写入字符数组,但在尝试使用 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/

相关文章:

c++ - C 和 Matlab : Why does this one line in Matlab become so many lines in C++ code generated by Matlab Coder?

c - 如何解释此调试错误

python - 为 c/c++ 代码编写 ctypes 包装器的正确方法

c - 我如何使用c套接字程序显示客户端地址?

c - 正则表达式不正确 c

捕获 SIGTERM,并 sleep 阻止它工作

CUDA并发执行

c - 使用 sscanf 解析文本文件的整数和浮点值

c - 返回后打印一些东西

c - 该程序的返回值为。 。 。 .至少可以说很奇怪