我写了一个读取文件的代码
下面的代码有什么问题,如果我打印任何 arrayItem,我总是得到最后一个文件名
#include <stdio.h>
#include <string.h>
char **get_files()
{
FILE *fp;
int status;
char file[1000];
char **files = NULL;
int i = 0;
/* Open the command for reading. */
fp = popen("ls", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
//exit;
}
while (fgets(file, sizeof(file)-1, fp) != NULL) {
files = (char **)realloc(files, (i + 1) * sizeof(char *));
//files[i] = (char *)malloc(sizeof(char));
files[i] = file;
i++;
}
printf("%s", files[0]);
return files;
}
int main()
{
char **files = NULL;
int i =0 ;
files = get_files("");
}
最佳答案
你应该使用
files[i] = strdup(file);
而不是
files[i] = file;
第二个版本仅让files[i]
指向始终相同的读取缓冲区。使用下一个 fgets
,您将覆盖 file
的内容,从而覆盖实际上指向同一位置的 file[i]
的内容在内存中。
事实上,最后,所有 file[0]
..file[n]
将指向与 file
相同的位置。
使用strdup(..)
,您可以分配一个新的缓冲区并将file
的内容复制到那里。
关于c - C 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3653907/