您可能不想使用std::endl,因为它会刷新输出流。
此外,如果您希望与 Windows(以及可能来自 Microsoft 的任何其他操作系统)兼容,则必须以二进制模式打开文件。微软默认以文本模式打开文件,这通常有一个没人想要的不兼容特性(ancient-DOS-backward-compatibility):它将每个“\n”替换为“\r\n”。
PGM 文件格式标头为:
"P5" + at least one whitespace (\n, \r, \t, space)
width (ascii decimal) + at least one whitespace (\n, \r, \t, space)
height (ascii decimal) + at least one whitespace (\n, \r, \t, space)
max gray value (ascii decimal) + EXACTLY ONE whitespace (\n, \r, \t, space)
这是将 pgm 输出到文件的示例:
#include <fstream>
const unsigned char* bitmap[MAXHEIGHT] = …;// pointers to each pixel row
{
std::ofstream f("test.pgm",std::ios_base::out
|std::ios_base::binary
|std::ios_base::trunc
);
int maxColorValue = 255;
f << "P5\n" << width << " " << height << "\n" << maxColorValue << "\n";
// std::endl == "\n" + std::flush
// we do not want std::flush here.
for(int i=0;i<height;++i)
f.write( reinterpret_cast<const char*>(bitmap[i]), width );
if(wannaFlush)
f << std::flush;
} // block scope closes file, which flushes anyway.