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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s