C++如何在内存中保存的文件流到另一个位置

问题描述:

我有记忆常规文本日志文件,C++如何在内存中保存的文件流到另一个位置

ofstream logfile; 

它被封装在一个Logger类,具有析构函数关闭该文件,

class Logger { 
    ofstream logfile; 
    ~Logger() { 
     logfile.close(); 
    } 
    ... 
} 

我想要做的是,在Logger析构函数,日志文件的另一副本保存到另一个目录。

这样做的最好方法是什么?

+1

你是问如何复制*文件*?还是你问如何使用你的退出流来执行该操作? – WhozCraig 2014-12-03 18:44:55

+0

@WhozCraig我想相同的流保存到另一个文件 – manatttta 2014-12-03 18:49:28

+0

'iostreams'只是缓冲过滤器,数据只是路过。不能从流中取回输出流中的内容。 – xbug 2014-12-03 20:19:50

#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

也许这是不是最好的方法,但它是一个工作之一。
您可以创建std::ofstream的新实例并将所有数据复制到该实例中。

+0

是的,这将是最简单的方法,但我想知道的替代方案,如果有一个 – manatttta 2014-12-03 18:49:53

+0

@manatttta我不知道有任何替代 – Quest 2014-12-03 19:15:45