简体   繁体   中英

Reading a binary file with fread

I am trying to read a bin with fread ? . The binary file I am reading has 1 million sets of data. However I am only getting 600+ and the data read is either 0 or -1.#QNAN0 . Am I using fread the right way?

struct Data {
    float time;
    float signal1;
    float signal2;
    float signal3;
};

long i;
static struct Data data[1000]; //(Solve by using static)

long openfile() {

  FILE *fp;
  char* filename = "Test_0012.bin";

  fp = fopen(filename, "rb");
  if (fp == NULL){
      printf("Could not open file %s",filename);
      return 1;
  }

  while(!feof(fp)){
    fread(&data, sizeof(data),1,fp);

    printf("%d\t", i);
    printf("%f\t", data[i].time);
    printf("%f\t", data[i].signal1);
    printf("%f\t", data[i].signal2);
    printf("%f\n", data[i].signal3);

    i++;
  }
  fclose(fp);
  return i;
}

You probably want something like this:

int i = 0;
do
{
  fread(&data[i], sizeof(struct Data), 1, fp);
} while (!feof(fp));

You want to read n times the size of struct Data , rather than once the whole array.

BTW you also need to check if there are no more than 1000 (which equals sizeof(data)/sizeof(data[0]) entries, and you need to check if the value returned by fread is the same as the number of elements you asked to read (1 in this case), otherwise a read error has occurred.

But there could also be a problem with the binary file itself, depending on how it has been generated. It would be helpful to see that code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM