I am writing some data to file using ofstream and the << operator. The program first generates the data to be written and puts it in a char memory block. I then write it to the file, however it seems that if there are any zeros in my data set, the write to the file ends at that zero and the program closes my file without writing everything down. Whats going on?
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <iomanip>
usingnamespace std;
void main ()
{
int dim = 1000;
unsignedchar * cadPart;
cadPart = newunsignedchar [dim * dim * dim];
stringstream index;
string fileName;
int pixleSum;
for (int k = 0; k < dim; k++)
{
cout << k << endl;
char * cadSlice;
cadSlice = newchar [dim * dim * 3];
fileName = ".bmp";
index.str("");
index << setw( 4 ) << setfill( '0' ) << k;
fileName = index.str() + fileName;
ifstream readBitmap;
readBitmap.open(fileName.c_str());
readBitmap.seekg(54, ios::beg);
readBitmap.read(cadSlice, (dim * dim)*3);
readBitmap.close();
for (int j = 0; j < dim; j++)
{
for (int i = 0; i < dim; i++)
{
pixleSum = 0;
pixleSum = unsignedchar (cadSlice[((dim - j - 1) * dim + i) * 3]) + unsignedchar (cadSlice[((dim - j - 1) * dim + i) * 3 + 1]) + unsignedchar (cadSlice[((dim - j - 1) * dim + i) * 3 + 2]);
if (pixleSum > 50) // threasholding for how dark the pixle is. 0 is black, 255 is white.
{
cadPart[((k * dim) + j) * dim + i] = 255;
}
else
{
cadPart[((k * dim) + j) * dim + i] = 1; // problem here.
}
}
}
delete [] cadSlice;
}
ofstream outputFile;
outputFile.open("3D CAD Part.txt");
outputFile << cadPart;
outputFile.close();
}
Referring to the comment "the problem is here":
Here i wish to have 0 instead of 1. However, if i have a zero here, the program stops writing my buffer to file when it first encounters the zero. I have a feeling that its writing my buffer to file thinking its a null terminated string...which is not what i want it to be.