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.
答案 0 :(得分:0)
1)您可以使用纪元时间作为文件名的一部分,而不是使用一个不会明显重置或重用的任意增量变量。
2)您可以使用QFileInfo,就像您可以将现有逻辑更改为
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());
}
该代码将删除较旧的文件,同时保留最近的10个文件。