读取纯文本PGM p5文件后读取数据字节

read bytes of data after reading plain text pgm p5 file

本文关键字:读取 数据 字节 文件 p5 文本 PGM      更新时间:2023-10-16

我正在尝试读取.pgm版本p5文件。头是纯文本,然后实际数据存储在纯字节。报头可以是任意长度。在纯文本中逐行读取后,我如何开始逐字节读取?

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;
}

使用ifstream::read读取二进制数据块并将其复制到缓冲区中。您可以从标题中的图像大小知道数据的大小。

如果你的矩阵对象有一个方法来获取一个地址,你可以直接复制它,或者把它读入一些临时缓冲区,然后复制到矩阵中。每次读取一个字节可能非常慢。