如何根据给定的文件名,在磁盘上所有目录中搜索,找到该文件所在的目录。
要求源代码。

解决方案 »

  1.   


    procedure FindFiles(APath: String);
    var
      FSearchRec,
      DSearchRec: TSearchRec;
      FindResult: integer;  function IsDirNotation(ADirName: String): Boolean;
      begin
        Result := (ADirName = '.') or (ADirName = '..');
      end;begin
      APath := GetDirectoryName(APath); // Obtain a valid directory name
      { Find the first occurrence of the specified file name }
      FindResult := FindFirst(APath+FFileName,faAnyFile+faHidden+
                              faSysFile+faReadOnly,FSearchRec);
      try
        { Continue to search for the files according to the specified
          mask. If found, add the files and their paths to the listbox.}
        while FindResult = 0 do
        begin
          lbFiles.Items.Add(LowerCase(APath+FSearchRec.Name));
          FindResult := FindNext(FSearchRec);
        end;    { Now search the sub-directories of this current directory. Do this
          by using FindFirst to loop through each subdirectory, then call
          FindFiles (this function) again. This recursive process will
          continue until all sub-directories have been searched. }
        FindResult := FindFirst(APath+'*.*', faDirectory, DSearchRec);    while FindResult = 0 do
        begin
          if ((DSearchRec.Attr and faDirectory) = faDirectory) and not
            IsDirNotation(DSearchRec.Name) then
            FindFiles(APath+DSearchRec.Name); // Recursion here
          FindResult := FindNext(DSearchRec);
        end;
      finally
        FindClose(FSearchRec);
      end;
    end;
      

  2.   

    procedure TForm1.MakeTree;
    var  Sr : TSearchRec;
         Err: integer;
    Begin
     Application.ProcessMessages;
     Err:=FindFirst('*.*',$37,Sr) ;
     While (Err = 0) do
      begin
       if Sr.Name[1]<>'.' then
       begin
         fn:=ExpandFileName(Sr.Name);
         if fn='your file name' then // do sth...
            //eg: Print(exteactfilepath(fn)); //获得所在目录
       end;   { Begin Recursion }
       If ((Sr.Attr and faDirectory)<>0)AND(Sr.Name[1] <> '.') then
       begin
         DirsSize:=DirsSize+Sr.Size;
         inc(DirsCount);
         ChDir(Sr.Name) ;
         MakeTree ;
         ChDir('..') ;
       end ;
       { End Recursion }
       Err:=FindNext(Sr) ;
      end ;
    End;//使用
    ChDir('d:\');
     MakeTree;