I created a program that simply allocates some memmory and writes the contents to a file.(i was trying to build the fractal contest for fun ). But some deviuos error has occured.
My code(below) always show '400 bytes written' but the file size is seen as 401, 402, 403... (ie, each time I run the program the file size increases by 1byte even though i deleted the file twice). This has previously happened when i binary read/write before.
Can any one please point out what exactly I am missing here?
P.S.this doesn't happen some times(But, that's very rare.).
Code:
class raw_image{
private:
unsigned char * matrix;
long int width, height;
public:
raw_image(){
matrix = 0;
width = height = 0;
}
~raw_image(){
if(matrix)delete[] matrix;
}
bool set(long int w, long int h){
if(matrix)return false;
width=w;
height = h;
if( (width>200) || (height>200) )return false;
if(! (matrix = new unsigned char [width*height]) )return false;
return true;
}
void send_to_file(fstream & file)const; //the problen seems to be here
void friend display(raw_image img); //just a waste fucntion to check...
};
//I used a loop other than a single 'write'
because the max possible size 200x200 won't fit in an 'int'.
so here might be the problem.
void raw_image::send_to_file(fstream & file)const{
long int size=0;
for(int i=0; i<width; i++){
file.write(matrix+(i*width), height);
size+=height;
}
cout<<"\n\n"<<size<<"bytes written...\n";
}
//waste function to check some things...
void display(raw_image img){
for(int i=0; i<img.height; i++){
for(int j=0; j<img.width; j++){
if(img.matrix[i*img.height+j])cout<<" 1";
else cout<<" 0";
}
cout<<endl;
}
}
int main(){
raw_image blah;
if(blah.set(20, 20))cout<<"Successful...\n\n";
display(blah);
fstream mfile("image.raw", ios::out);
if(!mfile)cout<<"\n\nError...\n\n";
else{
cout<<"Press any key to write...\n";
getch();
blah.send_to_file(mfile);
}
return 0;
}