c++ builder / fileIO > 指定日付以降のファイルだけ見つける


動作確認
C++ Builder XE4

TFile::Copy()を使って指定日付以降のファイルだけフォルダ単位でコピーしたいと考えていた。
TFile::Copy()自体には日付範囲指定はできないようだ。

TFile::GetFiles()でリストを取得することになる。

山本隆さんのblogにてGetFiles()使用時のフィルタ方法が掲載されている。
http://www.gesource.jp/weblog/?p=4509

上記を元に日付範囲指定をしようとしたが、timestampから日付範囲指定しようとした時に"const" "非const" "GetCurrentDateTime"などの部分でエラーが出た。

結局、以下の手順とすることにした。

  1. GetFiles()で指定のコピー元フォルダのサブフォルダ含めて全部のファイルリストを取得
  2. ループでまわしながらTFile::GetLastWriteTime()で日付範囲によるフィルタ
  3. フィルタ後のファイルリストを使ってTFile::Copy()で逐次コピーする

上記の2までの部分を以下に実装した。

Unit1.h
//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE で管理されるコンポーネント
    TButton *Button1;
    void __fastcall Button1Click(TObject *Sender);
private:    // ユーザー宣言
public:     // ユーザー宣言
    __fastcall TForm1(TComponent* Owner);
};


//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <IOUtils.hpp>
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    String path = L"D:\\TMP\\160718_someData";
    String searchPattern = L"*.*";
    TSearchOption option = TSearchOption::soAllDirectories;

    TStringDynArray fileList = TDirectory::GetFiles(path, searchPattern, option);
    int allcnt = fileList.Length;

    TStringList *lst = new TStringList();

    TDateTime filedt;
    for(int idx = 0; idx < fileList.Length; idx++) {
        filedt = TFile::GetLastWriteTime(fileList[idx]);
        if ( filedt < VarToDateTime("2016/05/24 12:00") ) {
            continue;
        }
        lst->Add(fileList[idx]);
    }

    String msg = IntToStr(lst->Count) + L"/" + IntToStr(allcnt);
    OutputDebugString(msg.c_str());

    delete lst;
    lst = NULL;
}
//---------------------------------------------------------------------------
結果
デバッグ出力: 177/261 プロセス Project1.exe (2384)

261あるファイルのうち、日付フィルタによって177個に絞りこまれた。

フォルダ内のファイルが増えたときのパフォーマンスが気にはなる。