C++如何在内存中保存的文件流到另一个位置
问题描述:
我有记忆常规文本日志文件,C++如何在内存中保存的文件流到另一个位置
ofstream logfile;
它被封装在一个Logger类,具有析构函数关闭该文件,
class Logger {
ofstream logfile;
~Logger() {
logfile.close();
}
...
}
我想要做的是,在Logger
析构函数,日志文件的另一副本保存到另一个目录。
这样做的最好方法是什么?
答
#include <iostream>
#include <fstream>
class Logger
{
private:
std::fstream logfile; //fstream allows both read and write open-mode.
std::fstream secondfile;
const char* second;
public:
Logger(const char* file, const char* second)
: logfile(), secondfile(), second(second)
{
//open for both read and write, the original logfile.
logfile.open(file, std::ios::in | std::ios::out | std::ios::trunc);
}
void Write(const char* str, size_t size)
{
logfile.write(str, size); //write to the current logfile.
}
~Logger()
{
logfile.seekg(0, std::ios::beg);
secondfile.open(second, std::ios::out); //open the second file for write only.
secondfile<<logfile.rdbuf(); //copy the original to the second directly..
//close both.
logfile.close();
secondfile.close();
}
};
int main()
{
Logger l("C:/Users/Tea/Desktop/Foo.txt", "C:/Users/Tea/Desktop/Bar.txt");
l.Write("HELLO", 5);
}
+0
不够好! :) – manatttta 2014-12-04 13:00:50
你是问如何复制*文件*?还是你问如何使用你的退出流来执行该操作? – WhozCraig 2014-12-03 18:44:55
@WhozCraig我想相同的流保存到另一个文件 – manatttta 2014-12-03 18:49:28
'iostreams'只是缓冲过滤器,数据只是路过。不能从流中取回输出流中的内容。 – xbug 2014-12-03 20:19:50