ida*_*hmu 7 c++ ofstream streambuf
我上课Writer有两个ofstream成员.
两个流都与同一输出文件相关联.我想在Writer::write方法中使用两个流,但要确保每个流写入实际输出文件的末尾.
码
class my_ofstream1:
public ofstream
{
// implement some functions.
// using internal, extended type of streambuf
};
class my_ofstream2:
public ofstream
{
// implement some functions.
// using internal, extended type of streambuf
// (not the same type as found in my_ofstream1)
};
class Writer
{
public:
void open(string path)
{
f1.open(path.c_str(),ios_base::out); f2.open(path.c_str(),ios_base::out);
}
void close()
{
f1.close(); f2.close();
}
void write()
{
string s1 = "some string 1";
string s2 = "some string 2";
f1.write(s1.c_str(), s1.size());
// TBD - ensure stream f2 writes to the end of the actual output file
assert(f1.tellp() == f2.tellp());
f2.write(s2.c_str(), s2.size());
}
private:
my_ofstream1 f1;
my_ofstream1 f2;
};
void main()
{
Writer w;
w.open("some_file.txt");
w.write();
w.close();
}
Run Code Online (Sandbox Code Playgroud)
问题
如何确保f2与f1?同步?意思是,在写入之前,流偏移f2必须与流偏移同步,f1反之亦然?
我不能使用函数 std :: ios :: rdbuf,因为每个都ofstream使用特殊的派生streambuf.所以通过使用rdbuf()我将失去必要的功能.
我尝试使用 Synchronizing Streams主题中的一些技术,但无法实现.
这看起来像你的两个类都使用过滤streambuf习惯用法。无论如何,不要从 派生类
std::ofstream,而是直接从 派生类ostream,并让它们都使用相同的std::filebuf对象。如果您正在使用过滤streambuf习惯用法,请不要让您的过滤streambuf的缓冲区;留到最后再说吧std::filebuf。
换句话说,您的“内部扩展类型的streambuf”应该包含一个指向最终接收器的指针,该指针将是a filebuf(但您的过滤streambuf不需要知道这一点)。像这样的函数sync,它们只是传递到最终目的地,并且它们永远不应该自己建立缓冲区,而是将所有内容传递到 filebuf。
| 归档时间: |
|
| 查看次数: |
2776 次 |
| 最近记录: |