gpt4 book ai didi

c - 在C中将当前目录中的所有文件列出为字符串

转载 作者:行者123 更新时间:2023-11-30 20:39:40 24 4
gpt4 key购买 nike

好吧,我试图将当前目录的所有文件列出到 C 中的字符串中。当前目录下的文件有:

myftpclient.c、myftpclient.o、myftpserver.c、myftpserver.o

char * list(void) 
{
DIR *dp; // directory var
struct dirent *ep;
char str[256] ;
int n = 0 ;
dp = opendir ("./");
if (dp != NULL)
{
while ((ep = readdir (dp)))
{
int curLen = strlen((ep->d_name)) ;
strncat(str, (ep->d_name), curLen) ;
strncat(str, "\n", 1) ;
n += curLen + 1 ;
}
str[n] = '\0' ;
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");

return str ;
}

这是我对它的调用:

char * str = malloc(256) ;
str = list() ;

打印字符串时的输出是:B0

这根本就不是正确的。我究竟做错了什么?

最佳答案

我在您的代码中发现以下问题。

  1. 您正在创建一个 char 数组,以仅保存 256 个字符。当保存目录条目名称和换行符所需的字符数超过 256 时,您将遇到内存访问越界的情况。

  2. 您将返回一个指向本地范围内定义的数组的指针。从函数返回后,该数组将无效。

  3. 您可以使用 strcat 代替 strncatstrncat 仅当您想要附加的字符数少于源中保存的字符数时才有用。

您可以通过以下方式解决这些问题:

  1. 使用mallocstr分配内存。

  2. 使用realloc增加为每个目录条目分配的内存。

  3. 确保在调用函数中释放list() 返回的内存。

这是一个应该可以工作的版本。

char * list(void) 
{
DIR *dp; // directory var
struct dirent *ep;
char* str = malloc(1);
int n = 0 ;
str[0] = '\0';
dp = opendir ("./");
if (dp != NULL)
{
while ((ep = readdir (dp)))
{
int curLen = strlen((ep->d_name)) ;
n += curLen + 2 ; // One of the terminating null and the
// other for the newline.
str = realloc(str, n);
strcat(str, (ep->d_name)) ;
strcat(str, "\n") ;
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");

return str;
}

关于c - 在C中将当前目录中的所有文件列出为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com