1

I am new to filing and have not much idea about it.

I have written a code that tries to read an ASCII .pgm file named owl.pgm and writes it as myowl.pgm file:

#include <fstream>
const int MAXHEIGHT=221;
unsigned char *bitmap[MAXHEIGHT]={'\0'} ;// pointers to each pixel row
int main()
{
    int width=201, height=221;
    std::ifstream ifile("owl.pgm",std::ios::in);
    std::ofstream ofile("myowl.pgm",std::ios::out);
    for(int i=0;i<height;++i)
    {
        for(int j=0;j<width;++j)
            ifile.read(bitmap[i][j],sizeof(bitmap));
    }
    ofile << "P2\n" << width << " " << height << "\n255\n";
    for(int i=0;i<height;++i)
    {
        for(int j=0;j<width;++j)
            ofile<<bitmap[i][j];
    }
}

By my code has some errors. I will be thankful if anybody help me in correcting it.

LihO
  • 41,190
  • 11
  • 99
  • 167
zorroz
  • 21
  • 2
  • 5

1 Answers1

2

The problem seems to be in the way you read pixels from input file:

std::ifstream ifile("owl.pgm",std::ios::in);
for(int i=0;i<height;++i)
{
    for(int j=0;j<width;++j)
        ifile.read(bitmap[i][j],sizeof(bitmap));
}

Problem 1: You need to make sure your program doesn't treat the header of this file as actual pixels of the image. See the header format of PGM. You'll most likely have to skip first 3 lines before reading the pixels.

Problem 2: You are trying to read whole bitmap at once, but you do that within a nested loop that was obviously meant to read the bitmap pixel by pixel.

Reading of pixels could look like this instead:

for(int i = 0; i < height; ++i)
{
    for(int j = 0; j < width; ++j)
        ifile >> bitmap[i][j];
}
LihO
  • 41,190
  • 11
  • 99
  • 167
  • I got an error when my program executes."Unhandled exception at 0x00418019 in owl.exe: 0xC0000005: Access violation writing location 0x00000000." I have changed code as your suggestion. Do you now help me in resolving this error. – zorroz Feb 25 '13 at 11:25
  • @zorroz: Hard to tell what exactly is the problem here. With my answer I just wanted to point out that you should consider the header before reading the actual data + showed a possible approach that would give you the right direction. In case you are stuck with this access violation and can't get it work, then post it as a new question :) – LihO Feb 25 '13 at 11:55