Ice
Ice

Reputation: 84

Deleting items in a folder after X elements, from oldest, in Qt

Basically I have a directory in which I want X elements at most to be stored, and after that every files added must trigger the removal of the oldest stored element. So I thought to order them by Time in QFileInfoList but sadly this becomes system time dependent (if the user turns the clock by Y hours the latest files added will be considered th oldest and thus removed). This is what I've written so far with the problem of system time in it:

void namespace::cleanStationLogoDir()
{
    QDir dir(DIR);
    if(!dir.exists())
    {
        //Create directory
        if(dir.mkpath(DIR))
        {
            //Ok result
        }
        else
        {
            qDebug() << "Unable to create dir.";
        }
    }

    QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Time);
    qDebug() << "files size: " << files.size();

    while(files.size() > X)
    {
        qDebug() << "Removed last element" << files.last().filePath();
        dir.remove(files.takeLast().filePath());
        qDebug() << "files size: " << logo_files.size();
    }
}

Do you know any other way to do this? I considered adding an incremental ID to the name of the files while I store them but after max_INT files this could turn out to be a roblem, or if I wrap the IDs to X elements then I'm not sure which to remove on the next file received.

Upvotes: 2

Views: 849

Answers (1)

Naumann
Naumann

Reputation: 417

1) You may use epoch time as part of your file name instead of using an arbitrary increment variable that will never resets or reused obviously.

2) You may use QFileInfo, like you may change your existing logic as

QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Time | QDir::Reversed);
const int  MAX_NUM_FILES_TO_RETAIN = 10

for(int index = files.size(); index > MAX_NUM_FILES_TO_RETAIN; --index)
{
     const QFileInfo& info = files.at(index -1);
     QFile::remove(info.absoluteFilePath());
}

The code will remove the older files while keeping the recent 10 files.

Upvotes: 2

Related Questions