Skip to content
File I/O
step 1/5

Reading — step 1 of 5

Learn

~1 min readExceptions and File I/O

Pascal has multiple file I/O APIs. Modern code uses TStringList, TFileStream, or TStreamReader/TStreamWriter.

Reading lines with TStringList:

uses Classes;

var
    lines: TStringList;
    i: integer;
begin
    lines := TStringList.Create;
    try
        lines.LoadFromFile('data.txt');
        for i := 0 to lines.Count - 1 do
            WriteLn(lines[i]);
    finally
        lines.Free;
    end;
end.

Writing:

lines.Add('hello');
lines.Add('world');
lines.SaveToFile('output.txt');

Streaming for large files:

var
    stream: TFileStream;
    buf: array[0..1023] of byte;
    bytesRead: integer;
begin
    stream := TFileStream.Create('big.bin', fmOpenRead);
    try
        while True do begin
            bytesRead := stream.Read(buf, SizeOf(buf));
            if bytesRead = 0 then break;
            ProcessChunk(buf, bytesRead);
        end;
    finally
        stream.Free;
    end;
end.

Modes:

  • fmOpenRead
  • fmOpenWrite
  • fmOpenReadWrite
  • fmCreate — create or truncate
  • fmShareDenyNone, fmShareExclusive, etc. — sharing flags

AssignFile/Reset/Rewrite — old Pascal style, still works:

var
    f: TextFile;
    line: string;
begin
    AssignFile(f, 'data.txt');
    Reset(f);                        // open for reading
    try
        while not Eof(f) do begin
            ReadLn(f, line);
            Process(line);
        end;
    finally
        CloseFile(f);
    end;
end.

Prefer the modern API for new code. Old code uses AssignFile.

For Judge0: stdin/stdout instead of files. The patterns shown here apply when you have a real filesystem.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…