4

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
....
Gabriel H. Nunes
  • 735
  • 8
  • 20
mac
  • 51
  • 1
  • 1
  • 8
  • Yes it's somewhat a duplicate question, and i did take a look at the forum prior to making this one. I still don't get it. – mac Jan 23 '17 at 03:20

2 Answers2

5

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

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;
} 
RoadRunner
  • 25,803
  • 6
  • 42
  • 75