Appending a new line in a file(log file) i

2019-02-21 09:44发布

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

3条回答
forever°为你锁心
2楼-- · 2019-02-21 10:04

Use something like:

#include <fstream>
#include <iostream>
using namespace std;
int main() {
  ofstream out("try.txt", ios::app);
  out << "Hello, world!\n";
  return 0;
}

The ios:app option makes the output get appended to the end of the file instead of deleting its contents.

查看更多
狗以群分
3楼-- · 2019-02-21 10:17

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-21 10:19

maybe you need to open the file with the append option. like this:

FILE * pFile;
pFile = fopen ("myfile.txt","a");

or this :

fstream filestr;
filestr.open ("test.txt", fstream::app)
查看更多
登录 后发表回答