Reading CSV File and Storing Values into an Array

Reading and storing values from csv file in an array using C

Simply read a line in a loop until there are no more lines

#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 10000
#define LARGEST_LINE 1000
#define LARGEST_ELEMENT 100

int main(void) {
int c1[MAX_ITEMS];
char c2[MAX_ITEMS][LARGEST_ELEMENT+1]; // large enough for each `c2`
char c3[MAX_ITEMS][LARGEST_ELEMENT+1];
char c4[MAX_ITEMS][LARGEST_ELEMENT+1];
char c5[MAX_ITEMS][LARGEST_ELEMENT+1];
int c6[MAX_ITEMS];
int c7[MAX_ITEMS];

int tmpc1;
char tmpc2[LARGEST_ELEMENT+1];
char tmpc3[LARGEST_ELEMENT+1];
char tmpc4[LARGEST_ELEMENT+1];
char tmpc5[LARGEST_ELEMENT+1];
int tmpc6;
int tmpc7;

int lineno = 0;
char buf[LARGEST_LINE]; // large enough for the largest line
while (fgets(buf, sizeof buf, fp1)) {
++lineno;
// no error, process line
if (sscanf(buf, "%d,"
"%" LARGEST_ELEMENT "[^,],"
"%" LARGEST_ELEMENT "[^,],"
"%" LARGEST_ELEMENT "[^,],"
"%" LARGEST_ELEMENT "[^,],"
"%d,%d",
&tmpd1, tmpc2, tmpc3, tmpc4, tmpc5, &tmpd6, &tmpd7) == 7) {
// line ok, copy tmp variables and update indexes
c1[i] = tmpd1;
strcpy(c2[i], tmpc2);
strcpy(c3[i], tmpc3);
strcpy(c4[i], tmpc4);
strcpy(c5[i], tmpc5);
c6[i] = tmpd6;
c7[i] = tmpd7;
i++;
} else {
// line with error, you may want to report to the user
fprintf(stderr, "line %d with error.\n", lineno);
}
}
// read "error", probably EOF; close file and report
fclose(fp1);
for (int j = 0; j < i; j++) {
printf("item #%d: %d, %s-%s-%s-%s, %d %d\n",
c1[j], c2[j], c3[j], c4[j], c5[j], c6[j], c7[j]);
}
return 0;
}

Also consider putting all those c arrays inside a struct and make 1 single array of that structure.

How to import a csv-file into a data array?

Assuming the CSV file is delimited with commas, the simplest way using the csv module in Python 3 would probably be:

import csv

with open('testfile.csv', newline='') as csvfile:
data = list(csv.reader(csvfile))

print(data)

You can specify other delimiters, such as tab characters, by specifying them when creating the csv.reader:

    data = list(csv.reader(csvfile, delimiter='\t'))

For Python 2, use open('testfile.csv', 'rb') to open the file.

Read lines of CSV file and put values into an Array

Ok so i got it.

I dont know why, but this code adds a " to the final of each line in my file like i said before. Ofcourse i did a test with the enclosure ($line = fgetcsv($file, 0, '|', ' " ') and nothing.
Since i was desperate i inverted the enclosure and i did ($line = fgetcsv($file, 0, '|', " ' ") and it works.
I don't know why PHP is treating the ' as a " but ok. Well it works now so hope this might help anyone in same situation. Here is full code:

while (($line = fgetcsv($file, 0, '|', "'")) !== FALSE) {

$OrderLines[] = $line;
}
fclose($file);


Related Topics



Leave a reply



Submit