Question

I've defined a binary file like this in C

FILE *gfp;
gfp = fopen(gridfiles, "wb");

The variable gridfiles stores the name of the file, and has been defined earlier. Now I write out two variables into the file.

for(yy = 0; yy < nfiley; yy++) {
   for(xx = 0; xx < nfilex; xx++) {
      filebx = beguv + xx*1E3;
      fileby = enduv - yy*1E3;
      fwrite(&filebx, sizeof(filebx), 1, gfp);
      fwrite(&fileby, sizeof(fileby), 1, gfp);
   }
}

If right after this code I

fseek(gfp, 0, SEEK_SET);
fread(&filebx, sizeof(filebx), 1, gfp);
fread(&fileby, sizeof(fileby), 1, gfp);
fprintf(stderr, "%f %f", filebx, fileby);

my output is

1000 15000

for the first two, which is as expected.

But if after some assorted other code (that doesn't involve these files at all) I repeat the fseek() etc., my output is

14000 14000

regardless of what I do. I've been trying to figure this out for a while now... anyone know what I'm doing wrong?

Was it helpful?

Solution

It's Undefined Behaviour to read from a stream which has been opened in write mode. You should make it:

gfp = fopen(gridfiles, "wb+");

if you plan to both read and write.

Also, as pointed out by @Kyle Jones in the comments above, you should get into the habit of checking the return status of fread/fwrite when doing file I/O - this would have caught your problem a lot earlier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top