0

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;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Sheng
  • 13
  • 1
  • 4
    Does this answer your question? [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Siguza Jan 25 '21 at 11:07
  • 4
    Is the result of `fread` equal to `sizeof(data)`? – Jay-Pi Jan 25 '21 at 11:10
  • 1
    If the file contains a million data sets, then an array of 1000 items isn't going to be large enough to store this data. – r3mainer Jan 25 '21 at 11:16
  • BTW: it's probably not a duplicate of [this](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong), there may be other unrelated problems – Jabberwocky Jan 25 '21 at 11:37

1 Answers1

2

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115