Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I quickly zero out the contents of a file?

Tags:

delphi

I want to terminate file that user selected from my program. I wrote this sample code:

var
  aFile: TFileStream;
Const
  FileAddr: String = 'H:\Akon.mp3';
  Buf: Byte = 0;
begin
  if FileExists(FileAddr) then
  begin
    // Open given file in file stream & rewrite it
    aFile:= TFileStream.Create(FileAddr, fmOpenReadWrite);
    try
      aFile.Seek(0, soFromBeginning);
      while aFile.Position <> aFile.Size do
        aFile.Write(Buf, 1);
    finally
      aFile.Free;
      ShowMessage('Finish');
    end;
  end;
end;

As you can see, I overwrite given file with 0 (null) value. This code works correctly, but the speed is very low in large files. I would like do this process in multithreaded code, but I tried some test some code and can't do it. For example, I create 4 threads that do this work to speed up this process.

Is there any way to speed up this process?

like image 816
Mojtaba Tajik Avatar asked Apr 22 '11 15:04

Mojtaba Tajik


1 Answers

I don't know if it could help you, but I think you could do better (than multithreading) writing to file a larger buffer.
For example you could initialize a buffer 16k wide and write directly to FileStream; you have only to check the last part of file, for which you write only a part of the full buffer.
Believe me, it will be really faster...

like image 66
Marco Avatar answered Oct 28 '22 02:10

Marco