The appearance of atoi, strcat, fixed size buffers, manual memory allocation and char*s is making my spidey sense tingle. There's a lot of potentially dangerous code in there.
An istream will typically do buffering for you and the usual extraction operators will perform just fine, here. Let's use them.
Really, the first thing you'll need to make is a function that skips over 'line comments', denoted by '#' in PPM files. Or better yet a type of object for which we can overload the stream extraction operator in order to skip comments.
After that you need to:
1. Read the magic number in to an std::string using the stream extraction operator
2. Read the image dimensions and pixel-component maximum in to integral objects, again using appropriate stream extraction operators
3. Read either a binary or 'ascii' raster depending on whether the magic number was 'P6' or 'P3'. For this you'd use the read() member function of an istream for binary, or stream extraction repeatedly for ascii.
You'll need error checks along the way of course, and you'll also need to look for line comments at appropriate points in the reading process.
Really, you could make the function look something like this:
bool read_ppm(std::istream &in, image &raster){ comment_skip comment; // implement appropriately std::string magic; long width = 0; long height = 0; long pixel_max = 0; // read the header in >> magic >> comment >> width >> comment >> height >> comment >> pixel_max; // check the header if (in && (magic == "P6" || magic == "P3") && width > 0 && height > 0 && pixel_max > 0 && pixel_max < 256) { // PPM "header" is valid if (magic == "P6") return read_ppm_raster_binary(in, raster); // implement appropriately else return read_ppm_rater_ascii(in, raster); // implement appropriately } return false;}// convenience wrapperbool read_ppm(const std::string &filename, image &raster){ std::ifstream in(filename.c_str(), std::ios::binary); return read_ppm(in, raster);}
IMHO, this is much more readable, not to mention free of memory leaks. There's also zero chance of buffer overrun occurring, by construction.
Edd