0

I have a problem with the function used to read the pgm file format to the memory .

I used the sources in the following link http://www.cse.unr.edu/~bebis/CS308/Code/ReadImage.cpp . You can find others in the same directory ; and some instructions in CS308 ; if you’re interested .

The problem is ifstream ifp fails ; and I think this piece of code maybe the reason ; but it looks fine with me .

Any ideas will be appreciated

charImage = (unsigned char *) new unsigned char [M*N];

 ifp.read( reinterpret_cast<char *>(charImage), (M*N)*sizeof(unsigned char));

 if (ifp.fail()) {
   cout << "Image " << fname << " has wrong size" << endl;
   exit(1);
 }
Tiana987642
  • 696
  • 2
  • 10
  • 28

2 Answers2

1

The problem is that your input file is not formatted properly. It should have enough data to fill charImage, but it doesn't, and this is why it's failing. Another possibility is that you are trying to run this code on windows, and need to open the file in binary mode.

Specifically (for the binary part) change:

 ifp.open(fname, ios::in);

to:

 ifp.open(fname, ios::in | ios::binary);

As an aside, it is generally inappropriate to cast the result of a new operator. Here, it's just redundant and doesn't make any sense.

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
  • Well ; I think nothing is wrong with the file format. I open it with irfanview and nothing seems wrong . I also tried a few images ; not only one . AFAIK ; the cast is used because the gray values (0-255) need unsigned char ; but ifstream::read need char to work – Tiana987642 Nov 04 '12 at 20:45
  • You're missing the point. It's already an `unsigned char *` when you use `new unsigned char`. It's redundant to cast it to `unsigned char *`. Also, have you tried the second part of my suggestion, which is that you need to open it in binary mode? – CrazyCasta Nov 04 '12 at 20:49
1

Anything using reinterpret_cast<...>() looks suspicious to me, to say the least. It is probably not the root of the problem, though. My personal guess is that the root of the problem is running the code on a Windows machine and not opening the file in binary mode. Try using

std::ifstream in("filename", std::ios_base:::binary);

Since the code opening the file isn't part of the question it is just a wild guess, though.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380