0

I am using tmpfile() to create a file (so it's automatically opened in binary mode).
Then I write some floats in it with fwrite(). All these floats are > 0.

The problem is that when I try to read these values (that are >0) back with fread(), I get negative values!

The values I write are out[i][j][couche] which are OK (it is impossible for them to be <0 because of their definition). The problem is at the end (fread).

void flou_bis (FILE * fp, PIXRVB **out, PIXRVB **in, int np, int nl, int rayon, int couche){
    int i,j,k,l,nb;
    float ret1, ret2;
    float rCouche;

    /* Other things not relevant..
    (process the values of array out[][][] ...)*/

    for (i=0; i<nl; i++)
    {
        for (j=0; j<np; j++)
        {
            fwrite ( &(out[i][j][couche]) , sizeof(float), 1, fp);
        }
    }

    rewind(fp);
    /*fsync(fp); // Useless
    rewind(fp);*/

    printf("%d float read\n", fread ( &ret2, sizeof(float), 1, fp)); /*Here is the problem!!! */
    printf("%f\n", ret2);
}
AusCBloke
  • 18,014
  • 6
  • 40
  • 44
user1493046
  • 352
  • 1
  • 3
  • 17
  • What parameters are you passing into `fopen()`? – Mysticial Oct 03 '12 at 06:59
  • are you positive you're writing positive values? is it possible your handling of the "out" pointer is wrong and you end up fwrite-ing from different memory than you want? – Roland Oct 03 '12 at 07:02
  • maybe add "if (i==0 && j==0) printf("first float %f\n", out[0][0][couche]);" to see what you actually write... – Roland Oct 03 '12 at 07:03
  • @Mysticial: I don't call fopen since tmpfile() opens the file automatically – user1493046 Oct 03 '12 at 07:06
  • @Roland: I don't know if the values written are correct but a printf of the array out[][][] just before writting its values is OK – user1493046 Oct 03 '12 at 07:06
  • @Roland "if (i==0 && j==0) printf("first float %f\n", out[0][0][couche]);" returns 196.000. It's normal – user1493046 Oct 03 '12 at 07:12

2 Answers2

0

You should:

  1. Print out the value you're accessing in out, to verify that the indexing is working, both as float and as bytes.
  2. Check that fwrite() doesn't fail.
  3. Print the contents of the file.
unwind
  • 391,730
  • 64
  • 469
  • 606
0

Problem solved, I needed to create a temp variable to force the cast:

float ent = (float) out[i][j][couche];
fwrite ( &ent, sizeof(float), 1, fp);

without the (float) it doesn't work, I have no idea why Thank you all for helping ;)

user1493046
  • 352
  • 1
  • 3
  • 17