我的班级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();
}
问题
如何确保f2
与 同步f1
?意思是,在写入之前,流偏移量f2
必须与流偏移量同步,f1
反之亦然?
我不能使用函数std::ios::rdbuf因为每个都ofstream
使用特殊的 derivedstreambuf
。所以通过使用rdbuf()
我会失去必要的功能。
我尝试使用同步流主题中的一些技术,但无法实现。