我正在尝试创建自己的文件格式。我要存储图像文件
以及该文件中的一些文字说明。
文件格式将是这样的:

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/

10-11 22:52
查看更多