0

I'm trying to read a .pgm version p5 file. The header is in plain text then the actual data is stored in plain bytes. The header can be an arbitrary length. I how can I start reading byte by byte after reading in the plain text line by line?

int main()
{
//Declare
    int rows = 0, cols = 0, maxVal = 0;
    ifstream infile("image.pgm");
    string inputLine = "";
    string trash = "";

    //First line "P5"
    getline(infile,inputLine);

    //ignore lines with comments
    getline(infile,trash);
    while (trash[0] == '#')
    {
        getline(infile,trash);
    }
    //get the rows and cols
    istringstream iss(trash);
    getline(iss, inputLine, ' ');
    rows = atoi(inputLine.c_str());
    getline(iss, inputLine, ' ');
    cols = atoi(inputLine.c_str());
    //get the last plain text line maxval
    getline(infile,inputLine);
    maxVal = atoi(inputLine.c_str());

    //Now start reading individual bites



    Matrix<int, rows, cols> m;

    //now comes the data
    for(i = 0; i<rows; i++)
    {
        for(j = 0; j < cols; j++)
        {
            //store data into matrix
        }
    }




    system("Pause");
    return 0;
}

1 Answers1

0

Use ifstream::read to read a block of binary data and copy it into a buffer. You know the size of data from the image size in the header.

If your matrix object has a method to get an address you can copy it directly, or read it into some temporary buffer and then copy that into the Matrix. Reading a byte a time is likely to be very slow.

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263