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

最后都变了- 提交于 2019-12-01 02:06:36

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.

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!