Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

Monday, 1 July 2013

Delete files with a wildcard

Here is how to delete files with a wildcard. It requires SysUtls in the uses clause.

procedure DeleteFiles(FilePath, Wildcard: string);
var cSearchRec: TSearchRec;
    iFind     : integer;
    sPath     : string;
begin
    sPath := IncludeTrailingPathDelimiter(FilePath);
    iFind := FindFirst(sPath + Wildcard, faAnyFile, cSearchRec);
    while iFind = 0 do
    begin
        DeleteFile(sPath + cSearchRec.Name);
        iFind := FindNext(cSearchRec);
    end;
    FindClose(cSearchRec);

end;

In the while loop you can add additional conditions, like only files that have a specific prefix e.g.

if Pos(fPrefix, Copy(cSearchRec.Name, 0, Length(fPrefix))) > 0 then

Tuesday, 4 December 2012

How to copy files in Delphi

Here are 2 methods for copying files in Delphi.

Method 1:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
 s, t: TFileStream;
begin
    s := TFileStream.Create(SourceFilename, fmOpenRead);
    try
      t := TFileStream.Create(TargetFilename, fmOpenwrite or fmCreate);
      try
        t.CopyFrom(s, s.size);
      finally
        t.free;
      end;
    finally
        s.free;
    end;
end;

Method 2:

procedure FileCopy(const SourceFilename, TargetFilename: string);
var   
  fromF,toF: file;
  numRead, numWritten: word;
  buf: array[1..2048] of char;
begin

  AssignFile(fromF, SourceFilename);
  Reset(fromF, 1);
  AssignFile(toF, TargetFilename);
  Rewrite(ToF, 1); 
  repeat 
    BlockRead(fromF, buf, SizeOF(Buf), numRead);
    BlockWrite(toF, buf, numRead, numWritten);
  until (numRead = 0) or (numWritten <> numRead);
  CloseFile(fromF);
  CloseFile(toF); 
end;