This is a classical problem, but I can not find a simple solution.
I have an input file like:
1 3 9 13 23 25 34 36 38 40 52 54 59
2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114
2 4 9 15 23 27 34 36 63 67 76 85 86 90 93 99 108 115
1 25 34 36 38 41 52 54 59 63 67 76 85 86 90 93 98 107 113
2 3 9 16 24 28
2 3 10 14 23 26 34 36 39 41 52 55 59 63 67 76
Lines of different number of integers separated by a space.
I would like to parse them in an array, and separate each line with a marker, let say -1.
The difficulty is that I must handle integers and line returns.
Here my existing code, it loops upon the scanf loop (because scanf can not begin at a given position).
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <data file> <nb transactions> <nb items>\n", argv[0]);
return 1;
}
FILE * file;
file = fopen (argv[1],"r");
if (file==NULL) {
fprintf(stderr, "Error: can not open %s\n", argv[1]);
fclose(file);
return 1;
}
int nb_trans = atoi(argv[2]);
int nb_items = atoi(argv[3]);
int *bdd = malloc(sizeof(int) * (nb_trans + nb_items));
char line[1024];
int i = 0;
while ( fgets(line, 1024, file) ) {
int item;
while ( sscanf (line, "%d ", &item )){
printf("%s %d %d\n", line, i, item);
bdd[i++] = item;
}
bdd[i++] = -1;
}
for ( i = 0; i < nb_trans + nb_items; i++ ) {
printf("%d ", bdd[i]);
}
printf("\n");
}