Zesss Zesss - 6 months ago 59
C Question

Read .CSV file in C

I Have a .csv file :

1;Jan;Kowalski;ul. Nowa;1a;11-234;Budry;123-123-456;jan@go.xxx;1980.05.13
2;Jerzy;Nowak;ul. Konopnicka;13a/3;00-900;Lichowice;(55)333-44-55;jer@wu.to;1990.03.23

and i need to read this in C. I have some code, but only for connection.


Hopefully this would get you started

See it live on http://ideone.com/l23He (using stdin)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* getfield(char* line, int num)
    const char* tok;
    for (tok = strtok(line, ";");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
        if (!--num)
            return tok;
    return NULL;

int main()
    FILE* stream = fopen("input", "r");

    char line[1024];
    while (fgets(line, 1024, stream))
        char* tmp = strdup(line);
        printf("Field 3 would be %s\n", getfield(tmp, 3));
        // NOTE strtok clobbers tmp


Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak