0

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?

3
  • 2
    You know, of course, that you should use const variables or #defines instead of the literal numbers 1278 and 968. Commented Sep 10, 2011 at 20:13
  • Yeah I usually do that.. its just for this sample code.. Thanks for mentioning it anyways.. Commented Sep 10, 2011 at 20:40
  • Always worthwhile pointing it out to any newbies who happen to read it too. Commented Sep 10, 2011 at 20:41

2 Answers 2

3
ifile>>Imagedata[i][j][k]; 

This is formatted input, it eats 'whitespace' characters even though you specified ios::binary. Use

Imagedata[i][j][k] = ifile.get(); 

Even better, allocate one big chunk of memory for the whole file and read it by one read call. What you do now is allocating a pointer for each pixel, which is very wasteful especially for 64-bit systems.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! this works.. also.. i found another way that worked.. i removed the third looping during the reading.. for(int i=0; i<1278; i++){ for(int j=0; j<968; j++){ ifile.read((char*)Imagedata[i][j],3); } }
0

I would bet this is because the skipws flag is set by default in file streams. Right after opening your fstreams, add file.unsetf( std::ios_base::skipws );

3 Comments

Would that be set even for a binary stream? That seems silly.
Yes, it does. I am not aware of the rationale, but has bitten me many times.
I wouldn't be able to tell if it needs fixing, without knowing the rationale for it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.