[fpc-pascal] Adding file to string to the RTL

Jer Haan jdehaan2014 at gmail.com
Tue Oct 6 09:42:14 CEST 2020


I use this function to read a file into a string:

function ReadFile(const FileName: TFileName): String;
var
  InputFile: THandle;
  FileSize, BytesRead: Integer;
  Buffer: String='';
begin
  try
    InputFile := FileOpen(FileName, fmOpenRead);
    if InputFile = -1 then
      begin
        WriteLn(Format('Error opening file "%s".', [FileName]));
        Halt; // Exit?
      end;

    FileSize := FileSeek(InputFile, 0, fsFromEnd);
    SetLength(Buffer, FileSize);
    FileSeek(InputFile, 0, fsFromBeginning);

    BytesRead := FileRead(InputFile, Buffer[1], FileSize);

    if BytesRead < FileSize then
      begin
        WriteLn(Format('Error reading file "%s".', [FileName]));
        Halt; // Exit?
      end;

    Result := Buffer;
  finally
    FileClose(InputFile);
  end;
end;


On 6 Oct 2020, at 09:25, Luca Olivetti via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:

El 6/10/20 a les 9:01, Michael Van Canneyt via fpc-pascal ha escrit:

> A simple filecreate, allocate buffer, fileread, fileclose will probably be easiest.

Lazarus has a ReadFileToString in fileutil.

Bye
-- 
Luca

_______________________________________________
fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20201006/8cbbb168/attachment.htm>


More information about the fpc-pascal mailing list