c++ - 多个文件合二为一

标签 c++ image binary file-format

我正在尝试创建自己的文件格式。我想存储图像文件 以及该文件中的一些文本描述。 文件格式将是这样的:

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/

相关文章:

c++ - 如何向 QSortFilterProxyModel 添加额外的行

java - 如何使其他类可以全局访问图像?

将负二进制转换为十进制

C++ 2D数组内存分配

c++ - gdb - 防止在捕获/重新抛出情况下丢失回溯

c++ - 在 C++ 程序中包含 C 头文件

macos - 确定可执行文件(或库)是 32 位还是 64 位

java - Jasper 报告从 byte[] 插入图像

java - 从 Assets 文件夹中重新缩放图像以适合屏幕

search - 二分搜索是 O(log n) 还是 O(n log n)?