How to read csv file with c language

How to read csv file with c language

Each line of the csv file has a semicolon; Separated,
so we just need to read line by line, and then cut according to the semicolon to get the cell content.

#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("test.csv", "r");

    char line[1024];
	int linecount = 0;
    while (fgets(line, 1024, stream)) // Read line by line
    {
		linecount++
        char* tmp = strdup(line);
        printf("the text of %d row, 3 col is %s\n", getfield(tmp, 3));
        
        free(tmp);
    }
}
Sour‮al.www:ec‬utturi.com
Created Time:2017-08-29 10:14:35  Author:lautturi