我知道互联网上有很多教程,而其中大多数都在StackOverflow上针对该主题,但是在实现它时遇到了一些问题。除了求助,我别无选择。
[我正在尝试实现一个从文件中读取多行的功能,将它们存储到一个数组中,然后传回信息,以便我可以从中建立一个链表。
我的职能是:
void read_file(char *out_file, char* strings[])
{
int i = 0;
do{
pthread_mutex_lock(&out_file_mutex);
char content[1024];
int counter = 0;
FILE* fp = fopen(out_file, "r");
if (fp)
{
// for each line read and add to array
while (fscanf(fp, "%s", content) == 1)
{
strings[counter] = content;
counter++;
}
fclose(fp);
i = 21;
}
else
{
sleep(1);
}
pthread_mutex_unlock(&out_file_mutex);
}while( i < 20 );
}
我这样称呼它。
if( (access( "test.csv", 0 )) != -1 )
{
char *strings[1024];
read_file("test.csv", strings);
int num = sizeof(strings) / sizeof(strings[0]);
for(int i = 0; i< num - 1; i++)
{
if(strings[i] == NULL)
break;
listdata* ld = (listdata*)malloc(sizeof(listdata));
strcpy(ld->content, strings[i]);
ld->next = NULL;
add_data_at_end(ld);
}
}
我的问题是该函数正在传回仅包含最后一行的数组。
示例:
在文件中,我有以下几行。
Line1
Line2
Line3
Line4
回到for循环的主目录:
Line4
Line4
Line4
Line4
基本上就是最后一行*文件中有多少行。
感谢任何帮助,因为我看不到自己在做什么错。
content
是局部变量。因此,每次分配(指向它)时,实际上都指向内存中的同一位置。这就是您获得4次相同结果的原因。由于它位于堆栈上,因此实际上得到令人惊讶的结果令人惊讶。函数终止时,堆栈内存超出范围,可能会被覆盖。
您需要使用strdup
分配堆内存。
strings[counter] = strdup(content);
不要忘记检查内存分配是否成功。另外,您必须释放内存并调用free()
关于:
while (fscanf(fp, "%s", content) == 1)
{
strings[counter] = content;
这将[SAME]指针分配给strings[]
中的每个条目。
建议:
while (fscanf(fp, "%s", content) == 1)
{
strings[counter] = strdup( content );
并且,为避免内存泄漏,在退出程序之前,请将strings[]
中的每个指针传递给free()
并使调用free()
成为一个简单的循环,建议:
char *strings[1024] = {NULL};