我试图写在磁盘上的PPM文件。 PPM是一个简单的图像格式,由ASCII图像头和像素的字节数组的:的std :: ofstream的是加入回车(CR; r)后 n自动
P6\n
width height\n
255\n
[width*height*3 bytes total]
这是我的PPM类(简化):
class PPMImage
{
protected:
friend std::istream& operator >>(std::istream &inputStream, PPMImage &other);
friend std::ostream& operator <<(std::ostream&, const PPMImage&);
size_t width;
size_t height;
// eg. "P6"
std::string magicNumber;
// Normally 255
uint16_t maxBrightness;
std::vector<std::vector<ImagePixel>> pixels;
};
这是我的写图像std::ofstream
:
std::ostream& operator <<(std::ostream &output, const PPMImage &other) {
// Writing header - THIS IS WHERE THE PROBLEM IS!
output<<"P6\n"<<other.width<<'\n'<<other.height<<'\n'<<other.maxBrightness<<'\n';
// The rest is pretty much irrelevant
size_t position = output.tellp();
output.seekp(position+other.width*other.height*3);
// Force the stream to be specific size
const char zero = 200;
output.write(&zero, 1);
// Write the image
output.seekp(position);
for(size_t y=0, yl=other.height; y<yl; ++y) {
for(size_t x=0, xl=other.width; x<xl; ++x) {
output.write((char*)&(other.pixels[y][x].r), 1);
output.write((char*)&(other.pixels[y][x].g), 1);
output.write((char*)&(other.pixels[y][x].b), 1);
}
}
return output;
}
这是我如何使用这个API:
std::ofstream out;
out.open("copy.ppm");
if(!out.is_open()) {
// error and exit here
}
out<<image;
out.close();
图像似乎确定,除了以下事实:ofstream的在报头中的每\n
之前添加\r
:
P6\r\n
width height\r\n
255\r\n
[width*height*3 bytes total]
这是不可接受的。我试图改变这样的初始化代码:
std::ofstream out("copy.ppm", std::ios::binary);
// I wonder why I have to mention "copy.ppm" twice...
out.open("copy.ppm");
但是,这只是创建空文件。有人可以解释如何正确写入PPM wile无回车?
换句话说:如何正确初始化ofstream使它不写\r
?
ios :: binary是正确的,但它已经打开。你没有二进制模式再次打开它?如果我只是说if(out.is_open())out <<“hello \ n”;再想一想,不,我不能重现你的问题。即使我打电话打开第二次,但没有指定模式,这让我感到惊讶。 –
我得到一个空文件,我可以重现。也许它是特定于Windows的? –
我没有去调用一个ostream运算符的极端。我会尽力重现整个事情。 –