如何仅使用 std::filebuf 将数据(二进制模式)写入文件
How to write data(binary mode) in to a file only using std::filebuf?
请检查以下代码:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
char mybuffer[512];
std::filebuf* optr = new std::filebuf();
optr->pubsetbuf(mybuffer, 512);
const char sentence[] = "Sample sentence";
auto ptr = optr->open("bd.bin", std::ios::binary | std::ios::trunc | std::ios::out);
if (ptr) {
float fx = 13;
auto n = optr->sputn(sentence, sizeof(sentence) - 1);
n += optr->sputn(reinterpret_cast<const char*>(&fx), sizeof(fx));
optr->pubsync();
}
optr->close();
if(optr) { delete optr; }
return 0;
}
运行此程序后,没有数据写入文件,而 sputn
-> n
返回有效数量的写入字符(通过调试验证(。
您的代码在我的系统上运行良好,生成一个包含 19 个字符的bd.bin
。
确定这正是您构建和运行的内容吗?也许您正在使用有问题的编译器,或者磁盘空间不足或其他内容。
使用正确的工具来完成工作。 filebuf
只是流式传输到的缓冲区。在iostreams API中编写的实际内容是std::ostream
:
std::filebuf file;
if (file.open(...)) {
std::ostream os(&file);
os << sentence;
os.write(reinterpret_cast<const char*>(&fx), sizeof(fx));
}
记住使用<<
和write()
也更容易,而不是处理streambuf
API的神秘命名functinos的迷宫。
相关文章:
- C++二进制模式下写入和读取文件
- 二进制模式 + 格式化文本操作或文本模式 + 二进制数据操作 - 有意义吗?
- 我无法使用C ++以二进制模式保存数据
- std::ifstream 在二进制模式下,语言环境在 C++ 中
- 如何仅使用 std::filebuf 将数据(二进制模式)写入文件
- 为什么FWRITE在二进制模式下会慢得多
- 为什么使用char数组来存储以二进制模式打开的文件的内容
- C++文件二进制模式副本
- 使用二进制模式将数据结构写入文件
- 以二进制模式写入文件不起作用
- 如何在二进制模式下将 NULL 写入文件
- 使用本地二进制模式进行对象跟踪:更改检测ROI的大小
- 如何使用c++在二进制模式下将矢量写入文件
- 如何存储在二进制模式C++中读取的文件中的数据
- 找到与另一个二进制模式匹配的所有 2 位值,然后对它们求和
- 在二进制模式下使用格式化的IO操作
- 以二进制模式打印到STL(立体光刻)文件
- 为什么ofstream不在linux上以二进制模式编写utf16
- 以二进制模式扫描文件,并将十六进制字符解释为C++中的实际数字
- Fread()二进制模式在c++中不能正常工作