2

This is the WriteAppLog code I used to create a log that app produces but I want to override the previous log OR create a new file with a new name every time.

Can someone help me modify?

void WriteAppLog (const std::string &s) { std::ofstream file ("AppLog.txt", std::ios::app); file << "[" << Helper::DateTime().GetDateTimeString () << "]" << "\n" << s << std::endl << "\n"; file.close(); } 
4
  • If you’re using C++, please use the C++ tag. Commented Oct 14, 2018 at 14:38
  • 1
    If you don’t want the output appended, don’t use the append flag. But I think you’ll find that you do want to append messages. It is easier to see what was going on after the event if you have all the logged messages. Commented Oct 14, 2018 at 14:41
  • You don't need file.close(), the stream closes itself when going out of scope. Commented Oct 14, 2018 at 14:43
  • @skalet True, but closing the file manually is the only way to check for errors of the close operation. Commented Oct 14, 2018 at 16:58

1 Answer 1

2

The mode flag std::ios::app indicates that the output should be appended to the file. You have to use std::ios::out:

std::ofstream file ("AppLog.txt", std::ios::out); 

See std::ofstream


OR create a new file with a new name

If you want to check if a file exists, then you can try to open the file for reading and check by std::ios::good() if this succeeded:

bool exists( const std::string& fileName ) { std::ifstream infile(fileName.c_str()) return infile.good(); } 

Dependent on the result you can create a new file with a new name.

Sign up to request clarification or add additional context in comments.

1 Comment

Using the exist() function would pose a TOCTOU race condition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.