如果open()在另一个类方法中,则C ++ ofstream无法写入

时间:2012-03-03 19:55:13

标签: c++ scope ofstream

我有一个使用ofstream对象log的类FileTransfer。类的构造函数在ofstream对象上调用open(),logFileName在.h文件中具有默认值。

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

在另一个类方法sendFile()中,我使用流来记录事件。

bool FileTransfer::sendFile() {
    log << "Sender: starting on host " << localhost << endl;
}

当我这样时,没有任何内容写入日志文件。我已经尝试检查log.is_open()和good(),并且都返回true。

编辑:

int main() {
    FileTransfer * ft = new FileTransfer(); // open() is called
    ft -> sendFile(); 
}

如果我在输出操作之前调用FileTransfer :: sendFile()方法中的log.open(),那么输出就可以正常工作。

bool FileTransfer::sendFile() {
    log.open(logFileName);
    log << "Sender: starting on host " << localhost << endl;
}

为什么会这样做?

2 个答案:

答案 0 :(得分:2)

啊哈,我知道你有什么问题!您正在写入该文件,但实际上它是进入缓冲区并且在第一种情况下没有刷新(这有点随机)。

打印后添加以下行:

log.flush();

它应该解决你的问题。

答案 1 :(得分:0)

FileTransfer的构造函数应该是这样的。

FileTransfer::FileTransfer(char * logFileName) : log( logFileName ) {
}

这样,ofstream以正确的方式构建。而且无需调用open()。我也认为这是处理错误和创建对象的更好设计。