The code below tries to parse a file containing these 3 lines:
0 2 5 9 10 12
0 1 0 2 4 1 2 3 4 2 1 4
2 3 3 -1 4 4 -3 1 2 2 6 1
and stores them in these arrays:
int Line1[] = { 0, 2, 5, 9, 10, 12 };
int Line2[] = { 0, 1, 0, 2, 4, 1, 2, 3, 4, 2, 1, 4 };
double Line3[] = { 2, 3, 3, -1, 4, 4, -3, 1, 2, 2, 6, 1 };
However in practice the number of fields in the actual input file are not fixed. Hence they can be greater than 6, 12 and 12 for each line.
Is there any way I can generalize the define
and sscanf
for this purpose?
Here is the complete code:
#include <stdio.h>
#include <stdlib.h>
// This is hard coded
#define LINE1_COUNT 6
#define LINE2_COUNT 12
#define LINE3_COUNT 12
int main() {
int Line1[LINE1_COUNT], Line2[LINE2_COUNT] ;
float Line3[LINE1_COUNT] ;
int j, check;
FILE *file = fopen("test.dat","r");
if (file) {
char line[BUFSIZ];
if (fgets(line, BUFSIZ, file)) { // read line 1, integers
int *i = Line1;//for easier reading
check = sscanf(line, "%i%i%i%i%i%i", &i[0],&i[1],&i[2],&i[3],&i[4],&i[5]) ;
if (check != LINE1_COUNT){
fprintf(stderr, "Failed to read expected %d values from line 1\n", LINE1_COUNT);
exit(1);
}
}else fprintf(stderr, "Couldn't read line 1!\n");
if (fgets(line, BUFSIZ, file)) { // read line 2, integers
int *i = Line2;//for easier reading
check = sscanf(line, "%i%i%i%i%i%i%i%i%i%i%i%i",
&i[0],&i[1],&i[2],&i[3],&i[4],&i[5],&i[6],&i[7],&i[8],&i[9],&i[10],&i[11]) ;
if (check != LINE2_COUNT){
fprintf(stderr, "Failed to read expected %d values from line 2\n", LINE2_COUNT);
exit(1);
}
}else fprintf(stderr, "Couldn't read line 2!\n");
if (fgets(line, BUFSIZ, file)) { // read line 3, floats
float *f = Line3;//for easier reading
check = sscanf(line, "%f%f%f%f%f%f%f%f%f%f%f%f",
&f[0],&f[1],&f[2],&f[3],&f[4],&f[5],&f[6],&f[7],&f[8],&f[9],&f[10],&f[11]) ;
if (check != LINE3_COUNT){
fprintf(stderr, "Failed to read expected %d values from line 3\n", LINE3_COUNT);
exit(1);
}
}else fprintf(stderr, "Couldn't read line 3!\n");
fclose(file);
}else {
perror("test.dat");
}
for (j=0;j<LINE1_COUNT;j++){
printf("%i\t",Line1[j]);
}
printf("\n");
for (j=0;j<LINE2_COUNT;j++){
printf("%i\t",Line2[j]);
}
printf("\n");
for (j=0;j<LINE3_COUNT;j++){
printf("%f\t",Line3[j]);
}
printf("\n");
printf("Press return to exit");
getchar();
return 0;
}