In working on a logfile for an application, I needed to limit the size of the logfile to 1000 bytes. Since it is not possible to delete lines from a file in C++, I used the following steps:
Rename the logfile to a temporary name. Read the temporary file. Write the last 1000 bytes to a new logile. Delete the temporary file.
I tested my code on another machine (location: Desktop) and it worked perfectly. When I tested the exact same code inside the application (location of the logfile: /var/HHPVideoServer/log.txt, application is run as sudo), it has no effect. Here is the code:
void Log::clear()
{
system("mv /var/HHPVideoServer/log.txt /var/HHPVideoServer/log_tmp.txt");
std::fstream tempfile;
tempfile.open("/var/HHPVideoServer/log_tmp.txt", std::ios::in);
tempfile.seekg(-1000, std::ios::end);
std::ofstream::pos_type startlog = tempfile.tellg();
unsigned length = 1000;
char* wrtBuf = new char[length];
tempfile.read(wrtBuf, length);
tempfile.close();
tempfile.open("/var/HHPVideoServer/log.txt", std::ios::out);
tempfile << wrtBuf;
delete[] wrtBuf;
tempfile.close();
system("rm /var/HHPVideoServer/log_tmp.txt");
}
The libraries this needed are included, and both the test machine and the machine it works on are running Ubuntu 11.10. I can't figure out why it doesn't work in the application. Thanks.
Edit:
The function is simply called every time the log is written to (which works) by:
int Log::Write(std::string to_write) {
.
.
other code here
.
.
std:ofstream logfile;
logfile.seekp(0, std::ios::end);
std::ofstream::pos_type current = logfile.tellp();
if (current >= 1000)
{
clear();
}
return 0;
}