0

What am I doing wrong? The file is empty after it is run (it works for char). Dont know why.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main()
{
    float marks[256][6];
    FILE *f= fopen("test.bin", "rb+");
    fread(marks, sizeof(float), sizeof(marks), f);
    marks[0][0] = 50;
    marks[0][1] = 50;
    marks[0][2] = 50;
    marks[0][3] = 50;
    marks[0][4] = 50;
    marks[0][5] = 50;
    fwrite(marks, sizeof(float), sizeof(marks), f); // Is this correct?
    fclose(f);
}
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 2
    So you read 1536 `float` values from a binary file, change 6 of them and write all back? How do you check that it does not work? – mch Mar 12 '18 at 12:50
  • 1
    All I/O operations can fail. Check the return values of all `f****` functions. – user694733 Mar 12 '18 at 12:50
  • 3
    `sizeof(float), sizeof(marks)` forces to read/write too many bytes (`sizeof(float) * sizeof(marks)`). – user694733 Mar 12 '18 at 12:52
  • 3
    Do C files have separate read and write pointers, ie. no rewind required after the read? – Martin James Mar 12 '18 at 13:03
  • 1
    How did you determine that the file was empty after the run? (Please post the output of `ls -l test.bin` or equivalent.) – zwol Mar 12 '18 at 13:03
  • you can clearly see it have 0 kb space :| open it for your self tested with char it runs and saved ofc greater then 1 kb,and when i open that file of float its empty and open char one it have binaries – Ahsan Iqbal Mar 12 '18 at 13:11
  • I suspect the root problem here is the over-read, (@user694733), blasts 'f' so the write fails. Since the OP does not check the result of the fwrite, it goes unnoticed. – Martin James Mar 12 '18 at 13:12
  • As mentioned. Check the return value of both fread and fwrite. – klutt Mar 12 '18 at 13:14
  • Your code segfaults when I try it. You need to do some debugging. – klutt Mar 12 '18 at 13:15
  • You must check the results returned by systems calls and those that are thinly-wrapped like fread() and fwrite(). They can fail and you may then be led into logical errors while debugging:( – Martin James Mar 12 '18 at 13:16
  • yes i think its the `sizeof()` forces too many bytes so it cancel out can anyone give me a have what to write in that – Ahsan Iqbal Mar 12 '18 at 13:33

0 Answers0