Reputation: 3130
I have regular text log file in memory,
ofstream logfile;
It is encapsulated in a Logger class, with a destructor closing that file,
class Logger {
ofstream logfile;
~Logger() {
logfile.close();
}
...
}
What I want to do is, at the Logger
destructor, save another copy of log file to another directory.
What is the best way to do this?
Upvotes: 0
Views: 738
Reputation: 23495
#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);
}
Upvotes: 1
Reputation: 2843
Maybe this is not the best approach, but it's a working one.
You can create a new instance of std::ofstream
and copy all of your data into it.
Upvotes: 1