0

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

Van Le Thanh
  • 81
  • 1
  • 7
  • To make life simple: put an fgets(...) in place of feof(...), then use sscanf(...) instead of fscanf(...) – ulix Dec 19 '21 at 08:17
  • My teacher require I have to use fscanf – Van Le Thanh Dec 19 '21 at 08:17
  • 1
    What, more precisely, do you mean by "it's not work correct"? *How* does it not work correctly? What happens? Anyway, `while(!feof(...))` is [nearly always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Ture Pålsson Dec 19 '21 at 08:23
  • I want to get data from row 2:,3...The result will be: st[0].id: 6929245 and st[0].firstname:Martin...... – Van Le Thanh Dec 19 '21 at 08:26
  • Just understand `fscanf()` will provide a *fragile* way to read the .csv file where one formatting error will corrupt the read from that point forward unless you add code to consume the remainder of the line in the event of a *Matching-Failure*. Far better to read the complete line with `fgets()` into a buffer (character array) and then parse from the buffer with `sscanf()`. – David C. Rankin Dec 19 '21 at 08:44

1 Answers1

2

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.

ram914
  • 331
  • 4
  • 19