I am working on a program where I am reading data from multiple files in sequential directories. If one of the files is missing, the program will get the data from another file (in that directory). In both cases the data is written to arrays to be written to file at a later stage of the program. I am writing to screen the desired information as I read it--it is coming in correctly. However, if at any point I read from the secondary file, the first three values of the array1 are set to zero.
abbreviated version of the code:
Code:
while (i < max_num) {
if((dataFile = fopen(filename,"rb")) != NULL) {
fread(&array1[i],sizeof(float),1,dataFile);
fread(&array2[i],sizeof(float),1,dataFile);
fread(&dumf,sizeof(float),1,dataFile);
fread(&dumf,sizeof(float),1,dataFile);
fread(&array3[i],sizeof(float),1,dataFile);
close(dataFile);
}
else {
if ((dataFile = fopen(filename2,"r")) != NULL){
for (j=1;j<8; j++) {
fgets(&dum,MAX_LINE,dataFile); /* skip unneeded data lines */
}
fscanf(datafile,"%s%f",&dum,&array1[i]);
fscanf(datafile,"%s%f",&dum,&array2[i]);
for (j=1;j<8; j++) {
fgets(&dum,MAX_LINE,dataFile); /* skip unneeded data lines */
}
fscanf(datafile,"%s%f",&dum,&array3[i]);
close(dataFile);
}
cnt++;
i++;
} /* end while */
if (cnt > 1) {
outFile = fopen("mydata.dat", "w");
for (i=0; i<cnt; i++) {
fprintf (outFile,"%f %f %f \n",array1[i],array2[i],array3[i]);
}
}
How do I fix this? I don't understand how it is happening in the first place, since I have verified that the correct values are written to the array initially.
Thanks.