Wednesday, July 7, 2010

How to read/write a string from/to file fast

When I'm debugging large SQL inserts/updates I tend to use the following two functions
const
  szChar = SizeOf(Char);
/// 
///   saves a string to a file
/// 
procedure StringToFile(const s: string; const FileName: string);
var
  FileStream: TFileStream;
begin
  FileStream := TFileStream.Create(FileName, fmCreate);
  try
    FileStream.WriteBuffer(Pointer(s)^, (Length(s) * szChar));
  finally
    FreeAndNil(FileStream);
  end; // try
end;

/// 
///   returns the content of the file as a string
/// 
function StringFromFile(const FileName: string): string;
var
  FileStream: TFileStream;
begin
  FileStream := TFileStream.Create(FileName, fmOpenRead);
  try
    SetLength(Result, (FileStream.Size div szChar));
    FileStream.ReadBuffer(Pointer(Result)^, FileStream.Size);
  finally
    FreeAndNil(FileStream);
  end; // try
end;
this functions are pretty fast and you can easily find other usage for them.

4 comments:

  1. (Length(Result) * SizeOf(Char))

    ReplyDelete
  2. Fixed, thank you for noticing, when I've posted this I was still using Delphi 7, but of course there's no excuse for writing bad code ;-)

    ReplyDelete
  3. Awesome. Exactly what I was looking for. Worked like a gem.

    ReplyDelete
  4. This short and simple code really work like a gem!
    I have made a large Front/End for reading and writing based on these tiny simple examples. It has opened up a new world of programming for me :)

    ReplyDelete

Blogroll(General programming and Delphi feeds)