我正在尝试创建自己的文件格式。我想存储图像文件 以及该文件中的一些文本描述。 文件格式将是这样的:
image_file_size
image_data
desctiption_file_size
description_data
但没有'\n' 符号。 为此,我正在使用 std::ios::binary。这是一些代码, 描述了该过程(它是草图,不是最后一个变体): 写我的文件。
long long image_length, desctiption_length;
std::fstream m_out(output_file_path, std::ios::out |
std::ios::binary);
std::ifstream input_image(m_image_file_path.toUtf8().data());
input_image.seekg(0, std::ios::end);
image_length = input_image.tellg();
input_image.seekg(0, std::ios::beg);
// writing image length to output file
m_out.write( (const char *)&image_length, sizeof(long long) );
char *buffer = new char[image_length];
input.read(buffer, image_length);
// writing image to file
m_out.write(buffer, image_length);
// writing description file the same way
// ...
正在阅读我的文件。
std::fstream m_in(m_file_path.toUtf8().data(), std::ios::in );
long long xml_length, image_length;
m_in.seekg(0, std::ios::beg);
m_in.read((char *)&image_length, sizeof(long long));
m_in.seekg(sizeof(long long));
char *buffer = new char[image_length];
m_in.read(buffer, image_length );
std::fstream fs("E:\\Temp\\out.jpg");
fs.write(buffer, image_length);
现在图像 (E:\Temp\out.jpg) 损坏了。我正在看十六进制 编辑器,还有一些额外的位。
有人能帮我看看我做错了什么吗?
最佳答案
由于您到处都在存储和读取二进制数据,因此您应该以二进制模式打开和创建所有 文件。
在写入部分:
std::ifstream input_image(m_image_file_path.toUtf8().data(), std::ios::in | std::ios::binary);
阅读部分:
std::fstream m_in(m_file_path.toUtf8().data(), std::ios::in | std::ios::binary);
//...
std::fstream fs("E:\\Temp\\out.jpg", std::ios::out | std::ios::binary);
关于c++ - 多个文件合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7388907/