He made sure of the correctness of the recorded data by viewing them through a hex editor. So feel free to open the file for reading.

FILE* fp; fp = fopen("C:\\Users\\seven\\source\\repos\\NeCuda\\NeCuda\\input.bin", "rb"); if (fp == NULL) { fprintf(stderr, "Cannot open up file"); exit(EXIT_FAILURE); } 

I counted the number of bytes written to a binary file and divided by how much one byte it takes to find out the number of array elements.

 while ((ch = getc(fp)) != EOF) counter++; counter /= sizeof(int); 

I allocated an appropriate amount of memory and checked that memory was really allocated.

 temp = (int*)malloc(sizeof(int)*counter); if (temp == NULL) { fprintf(stderr, "Cannot give mem"); exit(EXIT_FAILURE); } 

Now I want to write in the newly created array the data from the file

 int k=fread(temp, sizeof(int), counter, fp); 

But nothing is written, the pointer (as the debugger is shown) points to garbage (trailing). fread returned 0 and wrote this zero to k - it means that fread did not work exactly. How to make fread write data from a file to temp?

Followed the tips below:

 fseek(fp, 0L, SEEK_END); counter=ftell(fp); temp = (int*)malloc(sizeof(int)*counter); if (temp == NULL) { fprintf(stderr, "Cannot give mem"); exit(EXIT_FAILURE); } fseek(fp, 0, SEEK_SET); int k=fread(temp, sizeof(int), counter, fp); show(temp); 

But still there is no result

In the debugger, I see that the pointer is: fp 0x000002c9f7afc840 {_Placeholder = 0x0000000000000000}

  • one
    so, and the stream that rewound after the first reading? - Fat-Zer
  • @ Fat-Zer, yes, it’s already done - Elvin
  • one
    more to determine the file size usually use a combination of fseek() / ftell() - Fat-Zer
  • one
    counter you now have the size in bytes; and you need - in int 'ah. - Harry

1 answer 1

After the first reading you went to the end of the file.

A subsequent attempt at fread turns to the end of the file — and, of course, is not able to read anything.

You need to go back to the beginning of the file using the fseek function.

Moreover, this

 while ((ch = getc(fp)) != EOF) counter++; 

could be replaced by

 fseek(fp,0,SEEK_END); counter = ftell(fp); 
  • rewind help? - Elvin
  • Yes, since this is a synonym for calling fseek(stream, 0, SEEK_SET); . But if, say, you would first go to some kind of title, i.e. you wouldn’t need to read from the beginning, then fseek more versatile. Moreover, you could not read all these characters one by one, but simply call fseek and end up at the end of the file, and ftell would tell you its size ... - Harry
  • , fseek and rewind did not help, is still not readable - Elvin
  • one
    See for yourself that everything is OK: ideone.com/lW7EGF Here I just added a piece to create a file for verification. - Harry
  • one
    Here you have the second option - with fseek / ftell - ideone.com/3Jrube - Harry