Read .CSV file in C

后端 未结 5 1043
温柔的废话
温柔的废话 2020-11-22 10:15

I Have a .csv file :

lp;imie;nazwisko;ulica;numer;kod;miejscowosc;telefon;email;data_ur
1;Jan;Kowalski;ul. Nowa;1a;11-234;Budry;123-123-456;jan@go.xxx;1980.         


        
5条回答
  •  悲哀的现实
    2020-11-22 10:19

    Hopefully this would get you started

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

    #include 
    #include 
    #include 
    
    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
            free(tmp);
        }
    }
    

    Output:

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

提交回复
热议问题