Home > Software engineering >  How to get data from CSV file to struct by C language?
How to get data from CSV file to struct by C language?

Time:12-19

I have an csv file (delimited by commas). I want to get data in this file to struct. But it's not work correct. And I want get data from row 2 (ignore header). Sorry if my English not good. Thank you for your help.

#include <stdio.h>

struct Student
{
    char id[7];
    char firstname[50];
    char lastname[50]; 
    char gender[6];
    char birthday[10];
    char department[5];
    char city[50];
};

int main()
{
    struct Student st[100];
    int n=0;   
    FILE *filename;
    filename = fopen("student.csv","r");
    while (!feof(filename))
    {
        fscanf(filename,"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]",st[n].id,st[n].firstname,st[n].lastname,st[n].gender,st[n].birthday, st[n].department,st[n].city);
        n  ;
    }    
    fclose(filename);
    printf("%s\n",st[0].id);
    printf("%s\n",st[0].firstname);
    printf("%s\n",st[0].lastname);
    printf("%s\n",st[0].gender);
    printf("%s\n",st[0].birthday);
    printf("%s\n",st[0].department);
    printf("%s\n",st[0].city);
    return 0;
}

enter image description here

enter image description here

CodePudding user response:

In CSV format at the end of each line, you usually don't have a comma, If that is the case in your CSV file too, then change the format you are providing to fscanf,

from this,

"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]"

to this,

"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]"

if you try to read till next comma , for the city field too, then you will end up reading the string city\n6929245 to st[n].city which is wrong and will result in an incorrect reading pattern and might end up in segfault.

And to avoid printing the first line, you can skip the index 0 in your st array, because the first line that you read will be stored in the 0th index of the st array and from index 1 will be your data.

  •  Tags:  
  • c
  • Related