This function designed to save some log to file, but by unknown reason data from file gets removed...
I suppose it accesses the file when its empty and writes it as empty (maybe some other form of double access)
It is unclear what your goal is here. Are you simply trying to limit the log file to 1002 lines?
Make sure to turn your compiler warnings all the way up. Line 6 should definitely be showing an error.
What is typically done is to open a log file for append using the std::ios::app flag. (You do not need to specify automatic flags.)
1 2 3 4 5
std::ofstream logFile( my_log_file_name.c_str(), std::ios::app );
...
logFile << "stuff" << std::endl; // automatically written to end of file
If you want to limit the file size, I recommend you do that at some point when normal logging operations are not happening, either before your program starts or when it properly terminates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void toss_old_log_lines( const std::size_t MAX_NUM_LOG_LINES = 1002 )
{
std::vector<std::string> lines;
{
std::ifstream f( my_log_file_name.c_str() );
std::string s;
while (getline( f, s ))
lines.push_back( s );
}
if (lines.count() <= MAX_NUM_LOG_LINES) return;
std::ofstream f( my_log_file_name.c_str() ); // open file for REWRITE
auto n = MAX_NUM_LOG_LINES - lines.count(); // skip the lines to toss
while (n < MAX_NUM_LOG_LINES) // write the remainder
f << lines[n++] << '\n';
}
That is just one (very simple) way to do it. Caveats apply.
Possibly something like which when adding a new line to the log file and the file then contains more then the required number of lines removes earlier lines.
if its anything other than just a dump, eg you are doing fancy stuff like keeping 1000 lines, then keep a line buffer (eg a circular buffer of strings or something else simple) and once it reaches the limit (every line is populated) then open the file, dump your whole buffer to it in binary quick write approach, then close it. If you don't have the whole buffer full, you can either do the same or append to existing, both are plenty efficient.