简体   繁体   English

如何使用 C 计算 csv 文件中的列数?

[英]How can i count the number of columns in a csv file using C?

I have a project in c where the program should show the number of lines and columns in a cvs file.我在 c 中有一个项目,其中程序应该显示 cvs 文件中的行数和列数。 I have already done the lines but i can't make it count the columns.我已经完成了这些行,但我无法计算列数。 I had an ideia in witch i could count the number of "," and add 1. It works but not in every csv file the columns are separeted by commas, so it doesn't work for every csv file.我有一个想法,我可以计算“,”的数量并加 1。它有效,但不是在每个 csv 文件中,列用逗号分隔,因此它不适用于每个 csv 文件。

My code:我的代码:

#include <stdio.h>
#define COMMA 44


file_info(){

    FILE *f;
    int countlines = 0;
    int countcols = 0;

    char c;

    f = fopen("moradas.csv", "r");

    if (f == NULL)
    {
        printf("Can't open file!");
        return 0;
    }

    for (c = getc(f); c != EOF; c = getc(f)){
    if (c == '\n') // Increment count if this character is newline
    countlines++;
    if ((c == COMMA) && (countlines == 0))
    countcols++;

    }


    fclose(f);
    printf("Lines: %d \n", countlines);
    printf("Cols: %d \n", countcols + 1);

    return 0;

}


main(){

    int option;

    printf("Chose option\n");
    scanf("%d", &option);

switch(option)
{
    case 1:
    file_info();
    break;

    case 2:
    printf("2\n");
    break;
    default:
    printf("Chose valid option!\n");
}
}

I don't think there is a way.我不认为有办法。 You have to know the type seperation before counting the columns.在计算列之前,您必须知道类型分隔。 Maybe you could give the character as a parameter to the function so the program knows what to count.也许您可以将字符作为参数提供给 function,以便程序知道要计算什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM