001
04.03.2011, 19:07 Uhr
0xdeadbeef
Gott (Operator)
|
It is possible, of course, and there are several trillion ways to do it. The specifics vary with the precise requirements - do you know an upper limit to the number of values per line, do you know an upper limit to the number of lines in a file, do all lines contain the same number of values and suchlike. A general approach for a simple case would be something like this:
C++: |
/* for getline */ #define _GNU_SOURCE
#include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
int main(void) { char *line = 0; size_t n = 0, row; int array[20][10]; // 20 lines, 10 values each
FILE *fd = fopen("your_file.csv");
for(row = 0; row < 20 && 1 != getline(&line, &n, fd); ++row) { char *token, *saveptr = line; size_t col;
for(col = 0, token = strtok_r(line, ';', &saveptr); col < 10 && token; ++col, token = strtok_r(NULL, ';', &saveptr)) { array[row][col] = atoi(token); } }
free(line); fclose(fd);
/* Use array here */
return 0; }
|
It is much more arduous work in C than in C++ to do this with unknown dimensions, so I'll touch on that if you need it and C++ is not an option. This piece of code doesn't check error conditions very well; for example, a line like
will yield a line of zeros in the array and not complain about broken input. I don't know if this is a problem for your use case.
So, not necessarily production-ready, but it should give you a place to start. -- Einfachheit ist Voraussetzung für Zuverlässigkeit. -- Edsger Wybe Dijkstra Dieser Post wurde am 04.03.2011 um 19:18 Uhr von 0xdeadbeef editiert. |