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.open("/var/HHPVideoServer/log.txt", std::ios::out);
tempfile << wrtBuf;
delete[] wrtBuf;
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.

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)

return 0;

Edited by iamthesgt: n/a

5 Years
Discussion Span
Last Post by iamthesgt

Well something must be different. My first recommendation is to attach a debugger, and figure out what exactly is failing. My second recommendation is to get rid of system(), and use rename() and unlink(); if you insist on system(), at least spell out explicit paths to mv and rm.


That's just it, nothing 'fails' - the code doesn't execute, even when placed directly into the WriteLog function. It's as if it is being skipped over. I did replace the system calls, and my test code still works, but it made no difference in the application. I did look it up and saw why to do it that way, so thanks for the tip.


The fault was mine - I had forgotten to copy the compiled application to the /usr/bin folder, so everytime I was just running the old application. Thanks for the tips you gave me though.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.