I have a class FileTransfer that uses an ofstream object, log. The class’ constructor calls open() on the ofstream object, with logFileName having a default value in the .h file.
class FileTransfer {
public:
FileTransfer(char *logFileName = "client log.txt");
bool sendFile();
ofstream log; // log file
};
FileTransfer::FileTransfer(char * logFileName) {
this -> logFileName = logFileName;
// Open log file
log.open(logFileName);
}
In another class method, sendFile(), I use the stream to log events.
bool FileTransfer::sendFile() {
log << "Sender: starting on host " << localhost << endl;
}
When I have it like this, nothing is written to the log file . I’ve tried checking log.is_open() and good() and both return true.
EDIT:
int main() {
FileTransfer * ft = new FileTransfer(); // open() is called
ft -> sendFile();
}
If I call log.open() in the method FileTransfer::sendFile() right before my output operations, then output works perfectly fine.
bool FileTransfer::sendFile() {
log.open(logFileName);
log << "Sender: starting on host " << localhost << endl;
}
Why does it do this?
Aha I know what is you problem! You are writing to the file, but actually it goes to a buffer and is not flushed in the first case (this is a bit random).
Add the following line after your printing:
It should fix your issue.