Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 實作:依時間區間篩選目錄下的檔名

監控或抓拍系統常會產生大量檔名內含時間戳的檔案,例如:

1970_01_01_00_05_07_picture_000000231.jpg
1970_01_01_00_05_08_picture_000000232.jpg
1970_01_01_00_05_10_picture_000000233.jpg
...

需求是:給定一段起訖時間,把落在區間內的檔案挑出來。由於檔名本身就是「年_月_日_時_分_秒」的固定格式,字串排序剛好等於時間排序,因此不必解析成時間結構,直接比對前 19 個字元即可。

程式碼

#include <QtCore/QCoreApplication>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    string str1 = "1970_01_01_00_44_00";   // 起
    string str2 = "1970_01_01_00_45_01";   // 迄

    DIR           *dp;
    struct dirent *dirp;

    if ((dp = opendir("/mnt/picture")) == NULL) {
        printf("Can not open\n\n");
        return -1;
    }

    vector<string> vecPicname;
    bool flag1 = false, flag2 = false;

    while ((dirp = readdir(dp)) != NULL) {
        if (dirp->d_name[0] == '.')
            continue;                      // 跳過 . 與 ..

        string strTemp = dirp->d_name;
        strTemp = strTemp.substr(0, 19);   // 取出時間戳部分

        if (strTemp.compare(str1) >= 0 && strTemp.compare(str2) <= 0) {
            cout << "hit: " << strTemp << endl;
            vecPicname.push_back(dirp->d_name);
        }

        if (strTemp.compare(str1) == 0) flag1 = true;
        if (strTemp.compare(str2) == 0) flag2 = true;
        if (flag1 && flag2) break;         // 起訖都找到即可提前結束
    }

    for (unsigned int i = 0; i < vecPicname.size(); i++)
        cout << "file: " << vecPicname[i] << endl;

    closedir(dp);
    return a.exec();
}

如此就能列出指定時間區間內所有想要的檔名與圖片。搭配的清理策略也很單純,例如每次刪除最早的 100 張抓拍圖:

for (int i = 0; i < 100; i++) {
    system("rm -f /sddisk/picture/$(ls /sddisk/picture -rt | sed -n '1p')");
}

實務提醒

  • readdir() 的回傳順序與檔案系統有關,不保證是時間序;若需要有序結果,請把符合條件的檔名收集後再 sort()。
  • 檔名前 19 字元必須嚴格固定為時間格式,否則 substr 比對會失準;實作前先確認命名規則。
  • 刪檔迴圈每次呼叫 ls+rm,檔案量大時非常慢,建議一次撈出清單後批次刪除。
  • 若只是要按時間篩選,find /sddisk/picture -newermt "..." ! -newermt "..." 會比自行解析檔名更直覺。
Copyright © Linux教程網 All Rights Reserved