简体   繁体   中英

How to read a CSV file in C

I am trying to read a CSV file of the following format:

5,455,78,5
12245,4,78
1,455,4557,1,8,9

I have managed to open the file but I have no idea how to interpret the data. All the data is written in the first column, but I do not know how many rows there are or how many entries there is in each row. This is my code for opening the file.

printf("File chosen is: %s",file);

int p=0;

FILE *myFile = NULL;

myFile = fopen(file,"r");

if (myFile == NULL)
{
    exit(1);
}

if (myFile != NULL)
{
    printf("\n\nFile read succesfully");
}

This should parse your csv. After opening you file, read each line using fgets . Loop through until fgets returns NULL which indicates no line could be read and you reached the end of your file. Use strtok to parse your line from fgets using the comma as your delimiter.

#include <stdio.h>  // file handling functions
#include <stdlib.h> // atoi
#include <string.h> // strtok

...

    char buffer[80];
    while (fgets(buffer, 80, myFile)) {
        // If you only need the first column of each row
        char *token = strtok(buffer, ",");
        if (token) {
            int n = atoi(token);
            printf("%d\n", n);
        }

        // If you need all the values in a row
        char *token = strtok(buffer, ",");
        while (token) { 
            // Just printing each integer here but handle as needed
            int n = atoi(token);
            printf("%d\n", n);

            token = strtok(NULL, ",");
        }
    }

...

Thank you for posting some code, but you don't mention what you wish to do with your data once you read it in.

I'll give you some pointers:

Use an array of known size to read your data into from the file and buffer it for processing. Run this in a loop. eg

  char buffer[1000];

  while (fgets(buffer, sizeof (buffer), myFile))
  {
    char *data = strtok(buffer, ",");

    printf("Data %s\n", data);
    /* Further processing of data */

    data = strtok(NULL, ",");

  }

  fclose(myFile);

Process that buffer using strtok to separate out your strings. The token is the data delimiter which should be ',' but I'm not clear on whether you also have a newline character in there, but it needs to be consistent.

Handle your strings returned above.

#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("yourfile.csv", "r");
    int i = 0;
    int j = 0;
    printf("Choose a line to be given its elements: ");
    scanf("%d", &j);
    char line[1024];
    while (fgets(line, 1024, stream))
    {
        char* tmp = _strdup(line);
        i++;
        printf("Element %d would be %s\n", i, getfield(tmp, j));
        free(tmp);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM