This question already has an answer here:
- Read .CSV file in C 4 answers
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
....
Start by defining your data structure:
Then you can read like this:
Now you have a 1D array of structs, one for each row.
You can just create an array of structs, as the other answer described.
Once you have the
struct
definition:Then you can create an array of structs like this:
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()
until2
values are not found.Here is some basic code you can use: