Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 appended with the current data (what ever is there in the log file)

Just to make it clear for example: I have a log file logging_20120409.log which keeps the timestamp on a daily basis. Suppose I run my project it writes to it the current timestamp. Now if I rerun it the previous timestamp gets replaced with it. I do not want this functionality. I want the previous time stamp along with the current time stamp.

Please help

like image 734
gandhigcpp Avatar asked Apr 09 '12 09:04

gandhigcpp


People also ask

How do you enter a new line in a text file?

You put the slash for the newline character backwards. It should be: "\n".

How do you add a log to a file?

The Append Log consists of a flag that indicates what to do if the specified log file already exists. The default value is true. When set to true, the log messages are appended to the file. When set to false, the file is truncated, and the messages are written to the empty file.

How do you create a new line in a text file in C++?

The endl function, part of C++'s standard function library inserts a newline character into your output sequence, pushing the subsequent text to the next output line. Note that endl must be free of quotation marks; otherwise, the program will treat it as a string.


1 Answers

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 <ios> #include <fstream>  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.

like image 174
Jerry Coffin Avatar answered Sep 22 '22 02:09

Jerry Coffin