Adam
Adam

Reputation: 1

How to read a csv file in C?

I am trying to read a CSV file in C. The CSV file contains one column and 1024 rows. The CSV file contains only decimal numbers. So far I have this code, but the numbers from the output and the CSV file do not match. The CSV file is called file.csv

enter image description here

enter image description here

int main(void)
{
    FILE *stream;
    errno_t err;

    err = fopen_s(&stream, "file.csv", "r");
    if (stream == NULL) {
        printf("\n file opening failed ");
        return -1;
    }

    double values[1024];
    int count;
    for (count = 0; count < 1024; count++) {

        double u = fscanf_s(stream, "%d", &values[count]);
        printf("%d\n", u);
    }

return(0);

}

Upvotes: 0

Views: 602

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222754

Scan into and print double objects using %lg, not %d.

The return type of fscanf_s is an int, not a double. Test it to see if the desired number of items were assigned (one, in your case), and, if not, print an error message and exit the program.

Upvotes: 1

Related Questions