I am opening a 3.5 MB file in C reading it into an unsigned char array Image data which I have initialized as follows:
unsigned char *** Imagedata;
Imagedata = new unsigned char**[1278];
for(int i=0; i<1278; i++){
Imagedata[i]= new unsigned char*[968];
for(int j=0; j<968; j++){
Imagedata[i][j]= new unsigned char[3];
}
}
Now i open the file and read it into the array as:
ifstream ifile;
ifile.open("abcde.raw", ios::in|ios::binary);
for(int i=0; i<1278; i++){
for(int j=0; j<968; j++){
for(int k=0; k<3; k++){
ifile>>Imagedata[i][j][k];
}
}
}
ifile.close();
The next step is to just rewrite the bytes into a new file.. which i call rawfile.. I have tried to achieve it like this:
ofstream myfile;
myfile.open("rawfile.raw", ios::out|ios::binary);
for(int i=0; i<1278; i++){
for(int j=0; j<968; j++){
myfile.write((char *)Imagedata[i][j],3*sizeof(unsigned char));
}
}
myfile.close();
It somehow doesn seem to work.. the image file that i get is garbage.. what could be the problem?
This is formatted input, it eats ‘whitespace’ characters even though you specified
ios::binary. UseEven better, allocate one big chunk of memory for the whole file and read it by one
readcall. What you do now is allocating a pointer for each pixel, which is very wasteful especially for 64-bit systems.