简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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