write a float buffer to a binary file

1.8k views Asked by At
  • I have a float buffer with the data of the ppm file. The buffer[0][0] is the 1st element and the buffer[3*width*height][0] is the last element of the data.
  • Buffer has elements like this. 1st = 117 2st= 135 3st = 122. It's red, green and blue.
  • The point is to write this data into a binary file!

I try this, getHeight() returns the Height and getWidth() the width of the data.

ofstream output(filename, ios::out | ios::binary);  
output.write((char *)buffer, img.getHeight() * img.getWidth() * 3);

Also i try this, for i=0 to i=3*height*width

fp = fopen(filename, "wb");
fwrite(reinterpret_cast<char*>(&buffer[i][0]), 1, 3*height*width, fp);
2

There are 2 answers

0
oreubens On

A float is 4 bytes each. fwrite() doesn't know of the type you're writing, so for the size, you need to also multiply by the size of each element.

fwrite(reinterpret_cast<char*>(&buffer[i][0]), 1, 3*height*width * sizeof(float), fp);
1
Islam Adel On
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {
     ofstream out("blah.txt");
     float val = 10.0f;

     out << fixed << setprecision(5) << val << endl;
     out.close();
     return 0;
}