【发布时间】:2021-08-16 10:53:15
【问题描述】:
我是 C 的新手。我正在尝试读取 .CSV 文件,然后解析每一行,然后将数据存储在指向结构的指针的动态数组中。不幸的是,我在实现中的某个地方出错了,这导致了无限循环。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dataSet {
char ID;
char postcode;
int population;
char contact;
double x;
double y;
}data;
int main(int argc, char* argv[]) {
char line[100] = "";
int count = 0;
int each = 0;
data *allData = NULL;
data *temp = NULL;
FILE *file = fopen("dataset.csv", "r");
if (file == NULL)
{
printf("Error! File null");
return 1;
}
while (fgets(line, sizeof line, file))
{
if(NULL == (temp = realloc(allData, sizeof(*allData) * (count + 1))))
{
fprintf(stderr, "realloc problem\n");
fclose(file);
free(allData);
return 0;
}
allData = temp;
if (6 == scanf(line, "%s, %s, %d, %s, %lf, %lf",
&allData[count].ID,
&allData[count].postcode,
&allData[count].population,
&allData[count].contact,
&allData[count].x,
&allData[count].y)) {
count++;
}
else {
printf("Problem with data\n");
}
}
fclose(file);
for (each = 0; each < count; each++)
{
printf("%s, %s, %d, %s, %lf, %lf\n",
&allData[count].ID,
&allData[count].postcode,
&allData[count].population,
&allData[count].contact,
&allData[count].x,
&allData[count].y);
}
free(allData);
return 0;
}
任何帮助或提示将不胜感激。
【问题讨论】:
-
%s格式将读取一个 string,并将 null-terminated 字符串写入您的内存指针指向。因此,即使是一个字母的字符串也需要 两个 字符的空间来包含空终止符。单个char变量只能容纳单个字符。 -
另外,在读取循环之后,变量
count将是您分配的数组中的元素数。但请记住,当用作索引时,此值将超出范围。考虑一下打印值的循环(您需要再次考虑 strings 与 characters)。 -
sscanf() 不能用于重要的不受信任的输入。相反,您可以创建一个有限状态机。此外,您使用的 realloc() 方案将导致二次行为。
-
您是不是要使用
sscanf而不是scanf? -
正如@alex01011 所说。首先扫描整个文件以确定大小,然后执行一个 malloc。