How to properly work with FileRead, FileWrite, buffers (or with TFileStream).
I need to read a whole text file to a String, then to write back a String to this file
Here are two functions doing what you want:
function StringFromFile(const FileName: TFileName): RawByteString;
var F: THandle;
Size: integer;
begin
result := '';
if FileName='' then
exit;
F := FileOpen(FileName,fmOpenRead or fmShareDenyNone);
if PtrInt(F)>=0 then begin
{$ifdef LINUX}
Size := FileSeek(F,0,soFromEnd);
FileSeek(F,0,soFromBeginning);
{$else}
Size := GetFileSize(F,nil);
{$endif}
SetLength(result,Size);
if FileRead(F,pointer(Result)^,Size)<>Size then
result := '';
FileClose(F);
end;
end;
function FileFromString(const Content: RawByteString; const FileName: TFileName;
FlushOnDisk: boolean=false): boolean;
var F: THandle;
L: integer;
begin
result := false;
F := FileCreate(FileName);
if PtrInt(F)<0 then
exit;
if pointer(Content)<>nil then
L := FileWrite(F,pointer(Content)^,length(Content)) else
L := 0;
result := (L=length(Content));
{$ifdef MSWINDOWS}
if FlushOnDisk then
FlushFileBuffers(F);
{$endif}
FileClose(F);
end;
They use low-level FileOpen/FIleSeek/FileRead/FileWrite functions.
And you can specify any fmShare*
option you need.
It uses a RawByteString
type, so it expects the text to be handled in a bytes-oriented way. It won't work with Unicode text file, but with Ansi Text. You'll have to set the appropriate code page if you want to interact with it using the string type since Delphi 2009.
Before Delphi 2009, just define:
type
RawByteString = AnsiString;