ifstream :: read不读取unsigned char,即使使用reinterpret_cast也是如此

时间:2016-10-30 23:49:27

标签: c++ ifstream reinterpret-cast unsigned-char

我试图让我的代码读取PPM图像(P3)并且它不能正常工作。我们的想法是获得3个无符号字符并将它们存储在RGB中。但目前它只会导致第一个角色而忽略其余角色。

Image Image::readImg(std::string const &filename) {
    std::ifstream ifs;
    ifs.open(filename.c_str(), std::ios::binary);
    Image _in;
    try {
        if (ifs.fail()) {
            throw("Can't open input file");
        }
        std::string header;
        int w, h, max;
        ifs >> header;
        if (strcmp(header.c_str(), "P3") != 0) throw("Can't read input file");
        ifs >> w >> h >> max;
        _in.init(w, h);
        ifs.ignore(256, '\n');
        unsigned char pix[3];
        for (int i = 0; i < h; ++i){
            for (int j = 0; j < w; ++j){
                ifs.read(reinterpret_cast<char *>(pix), 3);
                _in.pixels[i][j].R = pix[0];
                _in.pixels[i][j].G = pix[1];
                _in.pixels[i][j].B = pix[2];
            }
        }
        std::cout << "|" << _in.pixels[0][0].R << " " << _in.pixels[0][0].G << " " << _in.pixels[0][0].B << "|";
        ifs.close();
    }
    catch (const char *err) {
        fprintf(stderr, "%s\n", err);
        ifs.close();
    }
    return _in;
}

注意std :: cout应该在我的场景中输出| 186 0 255 |,而是我得到| 1 8 6 |。

编辑:在Notepad ++中打开文件(original.ppm),如下所示(UNIX / UTF-8):

P3
1024 768
255
186 0 255 186 0 255 186 0 255 186 0 255 186 0 255 186 0 255 186 1 255 
186 1 254 186 1 254 185 2 254 185 2 254 185 1 254 185 2 253 185 3 253 
185 2 252 185 3 252 185 3 252 185 3 252 185 3 251 184 4 251 184 4 251 
184 4 251 184 4 251 184 5 250 184 5 250 183 5 250 183 6 249 183 6 249 
183 6 249 183 6 248 183 7 249 183 7 249 183 7 248 183 7 247 183 8 247 
182 7 247 182 8 246 183 9 247 183 9 246 183 9 246 182 9 246 181 9 246 
182 9 246 181 10 245 182 10 245 181 10 244 181 10 245 181 11 244 181 11 244
...

结果应该是:     _in.pixels [0] [0] .R = 186     _in.pixels [0] [0] .G = 0     _in.pixels [0] [0] .B = 255 并继续收集文件中所有像素的RGB。

2 个答案:

答案 0 :(得分:0)

使用&gt;&gt;流中的操作默认跳过空格。

如果你想保留所有字符,那么(在你阅读之前):

ifs >> std::noskipws;

您可能还需要以二进制模式打开文件。但我认为没有必要。

如果你想在字符串中准确读取两个字节,可以使用它而不是getline:

std::string st;
st.resize(2);
ifs.read(&st[0], st.size());

答案 1 :(得分:0)

[更新]这应该有效:

int pix[3]; // not an unsigned char
...
ifs >> pix[0] >> pix[1] >> pix[2];

而不是:

ifs.read(reinterpret_cast<char *>(pix), 3);

就像宽度和高度一样吗?

ifs >> w >> h >> max;
相关问题