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

时间:2014-12-03 18:36:26

标签: c++ logging

我在内存中有常规的文本日志文件,

ofstream logfile;

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

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

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

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

#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);
}