写入 PGM 文件
Writing to PGM file
我正在尝试使用此代码编写一个pgm文件。
myfile << "P5" << endl;
myfile << sizeColumn << " " << sizeRow << endl;
myfile << Q << endl;
myfile.write( reinterpret_cast<char *>(image), (sizeRow*sizeColumn)*sizeof(unsigned char));
如果我尝试将其写入.txt文件,它已经写入了 char 表示形式。
如何将我的值写入 pgm 文件以使其正确显示?有没有人有任何链接,因为我找不到太多!
您可能
不想使用 std::endl,因为它会刷新输出流。
此外,如果您希望与Windows(可能还有Microsoft的任何其他操作系统)兼容,则必须以二进制模式打开文件。默认情况下,Microsoft以文本模式打开文件,这通常具有没有人再想要的不兼容功能(古代DOS-向后兼容性):它将每个""替换为"\r"。
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 << "P5n" << 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.
确保使用 ios::binary
标志以二进制模式打开文件。如果您使用的是 Windows,则可能需要将endl
替换为 "rn"
。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 这些PGM文件是如何编码的?
- 如何顺时针旋转PGM文件
- C++程序读取ppm和pgm文件,对其进行操作并输出.编译错误
- 编写一个C++ pgm 以从文件"input.txt"读取,每当遇到句点时插入换行符并将修改的内容写入"output.txt"
- 读取二进制16位流文件并写入16位PGM(C++)
- 写入 PGM 文件
- 使用visual C++读取pgm文件
- 读取纯文本PGM p5文件后读取数据字节
- 如何在c++中从pgm文件中读取数据
- 如何读取/写入ASCI.pgm文件
- 如何将.pgm纹理文件加载到openGL中