0

I have an array of floats that I want to output to a file in binary. My relevant code is as follows:

    FILE *binFile;

    binFile = fopen(fileName, "wb");

    if (binFile)
    {
          fwrite(completeList, sizeof(float), size, binFile);
    }

Now, completeList is a pointer to an array of floats I was talking about, and size is another parameter I'm passing it indicating how many elements there are.

When this is outputted to a binary file, opening that file shows a bunch of random ASCII characters. I know this is what I should expect, but when I put it through a hex editor it shows random crap.

What am I doing wrong?

EDIT:

My parsing code:

    FILE *bofFile = fopen(file, "rb");

    if(bofFile)
    {
        float *tempArray;

        fseek(bofFile, 0, SEEK_END);

        unsigned long int size = ftell(bofFile) / sizeof(float);

        tempArray = (float *)malloc(size);

        fread(tempArray, sizeof(float), size, bofFile);

        std::cout << tempArray[0];
    }
tshepang
  • 12,111
  • 21
  • 91
  • 136
Tassos S
  • 101
  • 4

2 Answers2

2

Don't know if this is related, but you have a fairly serious problem here:

tempArray = malloc(size);

You should change that to prevent buffer overrun:

tempArray = malloc(size * sizeof(float));

Oh, and you also forgot to seek back to the start of the file before reading (that would be why it's "giving you nothing"):

fseek(bofFile, 0, SEEK_SET);
paddy
  • 60,864
  • 6
  • 61
  • 103
0

How is your input file formatted? Your code assumes that it too will look 'random' when viewed in a text editor. Have you tried displaying the entire array, to ensure you are reading the data from the input file correctly? Also, you have a malloc() problem that someone else pointed out.

The binary representation of the IEEE floating point format is not intuitive, and it will look like random data.

wlformyd
  • 237
  • 2
  • 12