检索csv文件的列ID

时间:2011-02-24 08:07:30

标签: c linux file csv

我想询问是否有任何方法可以使用C编程检索csv文件的列号?默认情况下在csv文件中设置的那些数字以及行名称i-e:

A B C .............. Z AA AB AC ............

1 个答案:

答案 0 :(得分:2)

很抱歉兰迪,但你对此有一些很大的误解。 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
}
相关问题