using FSCANF to read mixed text/double files
Hi there,
I am trying to read a file that is only partly sequential; it contains strings between "arrays" of ints and arrays of doubles of different sizes.
The file is reported below. Although I could read it by a combination of fgets() and strtok() calls, I am trying to change my old way to read it into a more efficient and shorter way by using fscanf throughout.
The problem is that, from the way I wrote the algorithm, it apparently stops reading the file correctly once it reaches the intermediate strings END_ELEMENTS and COORDINATES (See below).
I believe that I am doing somethign wrong in the sequence of calling fscanf, but I can't understand why.
I hope someone can help with this. I am sure it is a common task to read mixed files.
I use programming for my work but I am not actually a programmer, so that reading files is at times tricky
Thank you in advance:
1) File to be read
Code:
ELEMENTS
1 2 4 3 1
2 5 7 4 2
3 4 8 6 3
4 7 9 8 4
END_ELEMENTS
COORDINATES
1 0.000000 10.000000
2 0.000000 5.000000
3 5.000000 10.000000
4 5.000000 5.000000
5 0.000000 0.000000
6 10.000000 10.000000
7 5.000000 0.000000
8 10.000000 5.000000
9 10.000000 0.000000
END_COORDINATES
2) My function that does that:
Code:
//Testing the code:
int nnodes = 9;
int nelem = 4;
char header[32];
int CONN[nelem][4];
double COORDS[nnodes][3];
//READ the FIRST LINE OF THE FILE: ELEMENTS
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
k = 1;
i = 0;
while( !feof(msh_file_ID)){
if(k <= nelem){
//Read CONN:
fscanf(msh_file_ID, "%d %d %d %d %d\n", &(CONN[k][0]), &(CONN[k][1]), &(CONN[k][2]), &(CONN[k][3]), &(CONN[k][4]) );
printf(" %d %d %d %d %d\n ", CONN[k][0], CONN[k][1], CONN[k][2], CONN[k][3], CONN[k][4] );
}
//Read the intermediate strings: "END_ELEMENTS" and "COORDINATES"
else if(k > nelem && k <= nelem+2){
//String END_ELEMENTS
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
//String COORDINATES
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
}
//Read COORDS
else if(k > nelem+2 && k <= nelem+2+nnodes){
fscanf(msh_file_ID, "%f %f %f", &COORDS[i][0],&COORDS[i][1],&COORDS[i][2]);
printf(" %f %f %f\n", COORDS[i][0], COORDS[i][1],COORDS[i][2]);
i++;
}
else
return;
k++;
}//END while