请检查以下代码:
#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
正在返回有效数量的 writtne 字符(通过调试验证)。