使用流写入具有临时缓冲区的文件
Write to file with temporary buffer using ofstream
在事先不知道长度的情况下,如何编写一系列以其长度开头的数字(二进制)?
我可以将数字序列写入临时缓冲区(例如buf.write()
),确定缓冲区长度,然后将缓冲区复制到ofstream
(例如ofs << buf
)吗?
由于您是以二进制模式写入文件,请为数量保留一个位置。
例如,让我们为数量设置一个32位的值。我们可以把它写在文件的开头:
uint32_t number_size = 0U;
// Open output file for read & write.
// Reserve space for the quantity by writing dummy value.
output_file.write((char *)&number_size, sizeof(number_size));
// Perform calculations & writing to file, incrementing "number_size"
// Write the number size to the top of the file:
output_file.seekp(0, SEEK_BEG);
output_file.write((char *)&number_size, sizeof(number_size));
您可以将数量变量放置在任何位置,只需记住其文件位置即可。完成后,查找该位置并将其写入。
相关文章:
- 将整个二进制文件读入缓冲区,然后以特定格式解析
- 从缓冲区读取/写入文件
- 如何将文件的一部分读取到std::list缓冲区?
- CSV文件未从缓冲区获取数据
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 使用大磁盘文件的 C++ 循环缓冲区
- 文件大小和缓冲区过冲
- 从文件中读取原始压缩缓冲区.jpg使用 jpeglib
- 多线程和共享资源:使用C++定期将数据从缓冲区(数据结构)复制到文件
- 如何在没有任何缓冲区的情况下将 stderr 重定向到文件?
- 使用平面缓冲区读取以前写入的二进制文件的数据
- 读取文件时字符缓冲区溢出
- 将随机数放入缓冲区以写入文件的有效方法是什么?
- 使用谷歌协议缓冲区 - 如何在.proto文件中定义字段
- 无法使用两种不同的频率填充 *.wav 文件的缓冲区
- 将文件读取为缓冲区,并避免在读取之间分裂线
- 将浮点缓冲区写入二进制文件
- 将图像缓冲区保存到Android上的文件
- 使用文件缓冲区循环加密文件
- 正在将明文AES 128密钥导出到缓冲区/文件Windows Crypto API c++