1

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.

Ice
  • 64
  • 1
  • 7
  • *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* -- In other words, an [LRU Cache](https://stackoverflow.com/questions/2504178/lru-cache-design). – PaulMcKenzie Dec 19 '18 at 11:37
  • why is sorting the files system time dependent? earlier time should be earlier, no matter what is the current time – 463035818_is_not_an_ai Dec 19 '18 at 11:37
  • @user463035818: I am on a linux embedded system and I think that time information in the file inodes are system time dependent since they are chaning accordingly to that. – Ice Dec 19 '18 at 11:42
  • @PaulMcKenzie: this might actually be a very good pointer, thank you. – Ice Dec 19 '18 at 14:10
  • if you have the logrotate package on your embedded Linux it can be useful. – Fryz Dec 19 '18 at 17:02

1 Answers1

1

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.

Naumann
  • 357
  • 2
  • 13