Original Post
hi, i just wann read a ppm file in c++ and place the rgb-values in a character array. i have written the following code to do this: prior to this, i have tried to use the read()-function of ifstream first, but it failed to write the contents into the character array: the failbit was set to 1, the eof bit, too. i have calculated the number of bytes to be read after reading the ppm header information. you can follow the calculation in my code. it should be correct. this is about a 256x256 pixel ppm file with 3 bytes per pixel for the rgb-values. i really don't understand why ifstreams arrives at eof too quickly. here's the ppmreader.h, just in case you need it: [Edited by - Promit on July 30, 2007 7:51:11 PM]
#include <ppmreader.h>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
PPMReader::PPMReader(char * filename) {
loadPPMFile(filename);
}
void PPMReader::loadPPMFile(char * filename) {
const int readBufferSize = 20;
ifstream ifs;
char buffer[readBufferSize];
ifs.open(filename, ifstream::in);
ifs.getline(buffer, readBufferSize);
ifs.getline(buffer, readBufferSize, ' ');
width = atoi(buffer);
ifs.getline(buffer, readBufferSize);
height = atoi(buffer);
ifs.getline(buffer, readBufferSize);
unsigned int bitDepth = atoi(buffer);
bytesPerPix = (bitDepth == 255) ? 3 : 6;
unsigned int imagePixs = width * height;
unsigned int imageBytes = imagePixs * bytesPerPix;
image = new char[imageBytes];
unsigned int bytesPerLn = width * bytesPerPix;
for (int i = 0; i < int(height); i++) {
char* tmp = new char[bytesPerLn];
ifs.getline(tmp, bytesPerLn);
strcat(image, tmp);
}
ifs.close();
}
unsigned int PPMReader::getBytesPerPix() {
return bytesPerPix;
}
#ifndef PPMREADER_H
#define PPMREADER_H
#include <fstream>
using namespace std;
class PPMReader {
private:
char * image;
unsigned int width;
unsigned int height;
unsigned int bytesPerPix;
public:
PPMReader(char * filename);
inline void getImage(char * &dest) { dest = image; };
inline unsigned int getWidth() { return width; };
inline unsigned int getHeight() { return height; };
void loadPPMFile(char * filename);
unsigned int getBytesPerPix();
};
#endif