質問

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);
 }
役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top