Writing Files in Pascal

Here’s the translation of the Go code example to Pascal, formatted in Markdown suitable for Hugo:

Writing files in Pascal follows similar patterns to the ones we saw earlier for reading.

program WritingFiles;

uses
  SysUtils, Classes;

procedure Check(E: Exception);
begin
  if E <> nil then
    raise E;
end;

var
  F: TextFile;
  S: TStringList;
  BytesWritten: Integer;

begin
  // To start, here's how to dump a string (or just bytes) into a file.
  S := TStringList.Create;
  try
    S.Add('hello');
    S.Add('pascal');
    S.SaveToFile('/tmp/dat1');
  finally
    S.Free;
  end;

  // For more granular writes, open a file for writing.
  AssignFile(F, '/tmp/dat2');
  try
    Rewrite(F);

    // You can write strings as you'd expect.
    Write(F, 'some'#10);
    BytesWritten := 5;
    WriteLn('wrote ', BytesWritten, ' bytes');

    // A WriteString is also available.
    Write(F, 'writes'#10);
    BytesWritten := 7;
    WriteLn('wrote ', BytesWritten, ' bytes');

    // In Pascal, there's no explicit sync, but we can close and reopen the file
    // to ensure writes are flushed to stable storage.
    CloseFile(F);
    Append(F);

    // Pascal doesn't have a built-in buffered writer, but we can use TStringList
    // to accumulate strings and write them in one go.
    S := TStringList.Create;
    try
      S.Add('buffered');
      S.SaveToFile('/tmp/dat2', TEncoding.ASCII, True);
      BytesWritten := Length('buffered'#10);
      WriteLn('wrote ', BytesWritten, ' bytes');
    finally
      S.Free;
    end;

  finally
    CloseFile(F);
  end;
end.

Try running the file-writing code:

$ fpc writing-files.pas
$ ./writing-files
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files:

$ cat /tmp/dat1
hello
pascal
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.