Appending a new line in a file(log file) in c++

前端 未结 3 2012
感情败类
感情败类 2021-01-17 07:37

I have a logging functionality and in this I have got log files. Now every time I run the program I want that previously written file should not get deleted and should be ap

3条回答
  •  隐瞒了意图╮
    2021-01-17 07:54

    You want to open the file in "append" mode, so it doesn't delete the previous contents of the file. You do that by specifying ios_base::app when you open the file:

    std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);
    

    For example, each time you run this, it will add one more line to the file:

    #include 
    #include 
    
    int main(){
        std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);
    
        log << "line\n";
        return 0;
    }
    

    So, the first time you run it, you get

    line
    

    The second time:

    line
    line
    

    and so on.

提交回复
热议问题