抱歉,兰迪,但您对此有一些很大的误解。 CSV 文件非常像您在记事本中创建的文本文件,其中单词/值之间恰好有逗号。如果你想在 C 中阅读它们,你可以使用 scanf() 解析每一行 - 或者:
-
编写一个只能处理一种特定字段布局的程序:如...
char name[128]; int age; int height_cm; int weight_kg;
while (scanf("%.128[^,],%d,%d,%d", name, &age, &height_cm, &weight_kg) == 4)
// do something with the values just read...
-
尝试将字段解析为各种类型,直到失败:
char buffer[128];
char delimiter;
int num_fields;
while ((num_fields = scanf("%.128[^,]%c", buffer, delimiter)) >= 1)
{
// use e.g. strtod to see if the field might be reasonably interpreted as a double
...
if (num_fields == 1 || delimiter != 'c')
break; // end of line...
}
根据以下评论/问题进行编辑:
抱歉 - 我只是不明白你在问什么。什么是“增加”数据?如果你的意思是文件有不同的行代表不同的行,并且有不止一列,那么是的,这是正常的,它可以通过我上面列出的方法来解析。如果您要问“如何保存行/列以供将来处理”,那么您可以使用字段创建结构(如果您知道要对列名和类型进行硬编码),或者使用数组(也许char 数据最初)。然后,您可以拥有这些结构/数组的数组(或链表,如果您有相应的库)。例如:
static const int Max_Persons = 1000;
struct Person { char name[128]; int age; int height_cm; int weight_kg; };
Person persons[Max_Persons];
int num_persons = 0; // how many read from CSV file so far?
while (scanf("%.128[^,],%d,%d,%d",
persons[num_persons].name, &persons[num_persons].age,
&persons[num_persons].height_cm,
&persons[num_persons].weight_kg) == 4)
if (++num_persons == Max_Persons)
{
printf("WARNING: can only handle the first %d people, ignoring rest\n",
Max_Persons);
break;
}
这将读取(从标准输入 - 如果您想直接从命名文件读取,请切换到使用 fopen() 和 fscanf())最多 MAX_LINES 个“Person”行。
如果您不知道需要使用我之前列出的替代(更复杂)方法的数据数量和类型:尝试传递每个字段直到失败,检查以逗号结尾的字段与文件结尾。离题且未经测试,例如:
struct Field { char buf[Max_Field_Len]; };
struct Row { Field r[Max_Columns]; };
Data Row[Max_Rows];
int num_columns = 0;
int current_column = 0;
int num_rows = 0;
int num_fields;
char delimiter;
while ((num_fields = scanf("%[^,]%c", Row[num_rows][current_column].buf, &delimiter)) >= 1)
{
if (++current_column > num_columns)
num_columns = current_column;
if (num_fields == 2 && delimiter != ',')
{
current_column = 0;
++num_rows;
}
else if (num_fields == 1)
break; // end-of-file
}