好的,我试图将当前目录目录的所有文件列为C中的String。 当前目录中的文件是:
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
哪个甚至没有接近正确。我究竟做错了什么?
答案 0 :(得分:0)
我在您的代码中看到以下问题。
您正在创建一个char
数组,仅保留256
个字符。当保存目录条目名称和换行符所需的字符数超过256
时,您将遇到超出范围的内存访问。
您正在返回指向本地范围中定义的数组的指针。从函数返回后,数组将无效。
您可以使用strcat
代替strncat
。 strncat
仅在您想要追加少于在源头保留的字符数时才有用。
您可以通过以下方式修复这些问题:
使用malloc
为str
分配内存。
使用realloc
增加每个目录条目的已分配内存。
确保free
在调用函数中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;
}