Reading .csv file into an array in C [duplicate]

2019-06-01 15:59发布

This question already has an answer here:

I am Currently trying to read a .csv file into an array in C. I'm somewhat on the fence on how to approach the problem. I've looked through many forums and related topic but I still can't grasp it. If someone could show me or break it down as simple as possible. That would be greatly appreciated. By the way, the contents of the .csv file is like this. The array should consist of just the alphabet and the number. I was thinking about using a 2-D array. Is that an appropriate solution?

A,1
B,2
C,3
....

标签: c csv parsing
2条回答
smile是对你的礼貌
2楼-- · 2019-06-01 16:31

Start by defining your data structure:

struct my_record {
    char name;
    int value;
};

Then you can read like this:

FILE* my_file = fopen(...);
struct my_record records[100];
size_t count = 0;
for (; count < sizeof(records)/sizeof(records[0]); ++count)
{
    int got = fscanf(my_file, "%c,%d", &records[count].name, &records[count].value);
    if (got != 2) break; // wrong number of tokens - maybe end of file
}
fclose(my_file);

Now you have a 1D array of structs, one for each row.

查看更多
我命由我不由天
3楼-- · 2019-06-01 16:37

You can just create an array of structs, as the other answer described.

Once you have the struct definition:

typedef struct {
    char letter;
    int number;
} record_t;

Then you can create an array of structs like this:

record_t records[26]; /* 26 letters in alphabet, can be anything you want */

Using a 2D array would be unnecessary, as wrapping the letter and number in a struct would be easier to handle.

In terms of reading your file, you can just read with fscanf() until 2 values are not found.

Here is some basic code you can use:

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

#define NUMLETTERS 26

typedef struct {
    char letter;
    int number;
} record_t;

int main(void) {
    FILE *fp;
    record_t records[NUMLETTERS];
    size_t count = 0;

    fp = fopen("letters.csv", "r");
    if (fp == NULL) {
        fprintf(stderr, "Error reading file\n");
        return 1;
    }

    while (fscanf(fp, " %c,%d", &records[count].letter, &records[count].number) == 2) {
        count++;
    }

    for (size_t i = 0; i < count; i++) {
        printf("%c,%d\n", records[i].letter, records[i].number);
    }

    fclose(fp);

    return 0;
} 
查看更多
登录 后发表回答