How to write into a text file in free pascal

There are many ways to write and read into and from text files in object pascal language.

The most simple ways is the old structured method:


var
  F: TextFile;
begin
  AssignFile(F, 'first.txt');
  Rewrite(F);
  Writeln(F, 'Hello world');
  Writeln(F, 'Second line');
  CloseFile(F);
end.

You can use also an object of TStringList class :


var
  List: TStringList;
begin
  List:= TStringList.Create;
  List.Add('Hello world');
  List.Add('Second line');
  List.SaveToFile('second.txt');
  List.Free;
end.

Or using object oriented TFileStream class:


var
  f: TFileStream;
  Line: string;
begin
  f:= TFileStream.Create('third.txt', fmCreate);
  Line:= 'First line' + #13#10;
  f.Write(Pointer(Line)^, Length(Line));
  Line:= 'Second line' + #13#10;
  f.Write(Pointer(Line)^, Length(Line));
  f.Free;
end.

Leave a comment