Search code examples
cmv

Renaming & moving my file based on the size is not always working in c. Why?


I have an application, written in C, which generates various data parameters that I am logging into a text file named debug_log.txt. Whenever this log file reaches 1 MB, I am renaming the filename with timestamp ex debug_log_20200106_133000.txt & moving it in same directory. I am then reopening debug_log.txt to log new parameters.

if(stat("/home/log/debug_log.txt", &statFiledbg) == 0) 
{
    if(statFiledbg.st_size >= 1048576) // 1MB
    { 
        current_time = time(0);
        strftime(time_buffer, sizeof(time_buffer), "%Y%m%d_%H-%M-%S", gmtime(&current_time));
        sprintf(strSysCmddbg, "mv /home/log/debug_log.txt /home/log/debug_log%s.txt", time_buffer);
        system(strSysCmddbg);
        fp_dbglog = freopen("/home/log/debug_log.txt", "w", fp_dbglog);
    }
}

The code works most of the time until it doesn't. After running the application for couple days, I see that debug_log.txt grows beyond 1 MB while the last moved & renamed log file is empty.

What could be the reason?


Solution

  • Use the rename function from the C standard library (in stdio.h) and check errno if it failed to know the exact reason why it is failing.

    When working with files, and I/O in general, there are many, many things that can go wrong.

    One of my senior developer in the company told me so. Is there anything wrong with using system()?

    Yes: it is unnecessary (C and POSIX provide you with a function for basic usages like this), nonportable (it assumes you are in a system that has a "mv"), slower (it needs to spawn another process) and wrong for many use cases (eg. here there is no way to know what exactly failed unless you save the textual output of mv).

    See questions and answers like Moving a file on Linux in C for an in-depth explanation.