3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FindFirstで読み取り専用ファイルのみ抽出する方法

Posted at

Attrパラメータに読み取り専用ファイルを示す「faReadOnly」を指定すればいいと早合点し、

sample1.pas
  if FindFirst(IncludeTrainlingBackslash(path) + '*.*', faReadOnly, searchRec) = 0 then begin
    //処理
  end;

とすると、path配下の読み取り専用以外のファイルも検出してしまい、
期待した結果を得られません。

Porque?

FindFirstのヘルプをよく読むと

「Attrパラメータには、すべての通常ファイル以外で検索対象に含めるべき特殊ファイルを指定します。」

とあります。
ここで、FindFirstのソースを見ると、

SysUtils.pasの一部
  faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
  F.ExcludeAttr := not Attr and faSpecial;
  //※ExcludeAttr;除外する属性

特殊ファイルとは非表示ファイル、システムファイル、ボリュームファイル、ディレクトリファイルのみを指すようです。

つまり。

FindFirstは(読み取り専用ファイル、アーカイブファイルを含む)通常ファイルと、Attrパラメータで指定した特殊ファイルを検索する関数だったのです。

では、読み取り専用ファイルを見つけたい場合にはどうするか。

以下のように、Attrパラメータはダミーで"faReadOnly"をしておき※、とりあえず通常ファイルだけを検索したあと、
TSearchRecのAttrを調べて絞りこむとよいようです。

sample2.pas
  if FindFirst(IncludeTrainlingBackslash(path) + '*.*', faReadOnly, searchRec) = 0 then begin
    repeat
      if (searchRec.Attr and faReadOnly) = faReadOnly then begin
        //処理
      end;
    until FindNext(searchRec) <> 0;
    FindClose(searchRec);
 end


FindFirstで"faAnyFile"を指定すると、検索対象に特殊ファイルも含むようになります。
というのも、faAnyFileのnot(2進数000000)とfaSpecial(2進数011110) との論理積は0000000、これが除外対象属性F.ExcludeAttrの値となります。つまり、除外対象となるファイル属性は無いってこと。
すると、特殊ファイルの分の余計にrepeat処理を行うことになります。
大した手間ではないのかもしれませんが。

Web上のサンプルソースで以下のようなのを散見するのですが、

sample3.pas
  if FindFirst(IncludeTrainlingBackslash(path) + '*.*', faAnyFile, searchRec) = 0 then begin
    repeat
      if (sr.Name = '.') or (sr.Name = '..') then Continue;
      //処理
    until FindNext(searchRec) <> 0;
    FindClose(searchRec);

わざわざ全属性ファイルを指定した上で、ディレクトリファイルを除外してます。
なぜだろう?

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?