0

我正在尝试读取 .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;
}
4

1 回答 1

0

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

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

于 2015-10-06T02:20:54.633 回答