Tuesday, October 6, 2009

How to wipe a file

Here is a nice method to wipe a file as many times as you want(can wait)

procedure WipeFile(
const FileName: String; (* file to be wiped *)
const Times: Integer = 1 (* how many times ? *)
);
type
(* wipe 4kb at a time *)
TBuffer = array[0..4095] of Byte;
(* size of TBuffer *)
const
szBuffer = sizeof(TBuffer);
var
(* we need to know how many bytes we have left *)
BytesLeft,
(* this is to know how bytes we write *)
BufferSize: Int64;
(* a buffer variable *)
buffer: TBuffer;
index: Integer;
(* we use a file stream to overwrite the file *)
theFile: TFileStream;
begin
(* open the file *)
theFile := TFilestream.Create(FileName, fmOpenReadWrite or fmShareExclusive);
try
(* fill buffer with 128 values *)
FillChar(buffer, szBuffer, 128);
(* how many times should we wipe it ? *)
for index := 1 to Times do begin
(* remaining bytes *)
BytesLeft := theFile.Size;
(* start/restart from the beginning of the file *)
theFile.Position := 0;
(* while not end-of-file... *)
while BytesLeft > 0 do begin
(* check how many bytes we have left *)
if BytesLeft > szBuffer then
(* if we have more than 4096 bytes left
then we only wipe 4096 bytes this time *)
BufferSize := szBuffer else
(* we have 4096 or less bytes left *)
BufferSize := BytesLeft;
(* overwrite the file(wipe) *)
theFile.WriteBuffer(Buffer, BufferSize);
(* update BytesLeft variable *)
BytesLeft := BytesLeft -BufferSize;
end;
end;
finally
(* free the file stream *)
FreeAndNil(theFile);
end;
(* ...finally delete the file, it should not be
possible to *undelete* it *)
Deletefile(FileName);
end;