0
votes

Assuming you're reading a PPM file like this:

ifstream img;
img.open("Image.ppm", ios::binary);
try
{
    if (img.fail())
    {
        throw("Can't open input file");
    }
    string header;
    int w, h, b;
    img >> header;
    cout << header << endl;
    if (header.compare("P6") != 0)
    {
        throw("Wrong format file. File needs to be P6 type!");
    }
    img >> w >> h >> b;
    cout << w << " " << h << " " << b << endl;
    if (b < 0 || b > 255)
    {
        throw("An error message"); 
    }
    img.ignore(256, '\n');
}
catch (const char *err) 
{
    fprintf(stderr, "%s\n", err);
    img.close();
}

And someone removed the width or height value in the header. Now b value will read an RGB number in byte form. Is there any possible case that the if-statement won't prevent the program from ending? In other words is there an optimized method to prevent such errors?

2
Read as a line (using getline), put string into an istringstream and use the string stream to parse the values. Should simplify error handling a little.Some programmer dude
You have also to take care with possible comments (line starting by #) included in the header too.J. Piquard
Yes i know. Gonna take care of that.Discordgr

2 Answers

0
votes

One possible problem: 1. Data after b is binary, so the b in your scenario could be non-ASCII and thus be 0, which could pass your test for error message.

0
votes

In the simplest case, if the R value happened to be the ASCII value for a digit (48-57), and the G value happened to be the ASCII value for space (32), b would end up with the value of the digit (and hence wouldn't fail the test.