Task

Read a file one character at a time, as opposed to reading the entire file at once.

The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).

The procedure should support the reading of files containing UTF8 encoded wide characters, returning whole characters for each consecutive read.

Related task

   Read a file line by line


 
program Read_a_file_character_by_character_UTF8;
 
{$APPTYPE CONSOLE}
 
uses
  System.SysUtils,
  System.Classes;
 
function GetNextCharacter(StreamReader: TStreamReader): char;
begin
  Result := chr(StreamReader.Read);
end;
 
const
  FileName: TFileName = 'input.txt';
 
begin
  if not FileExists(FileName) then
    raise Exception.Create('Error: File not exist.');
 
  var F := TStreamReader.Create(FileName, TEncoding.UTF8);
 
  while not F.EndOfStream do
  begin
    var c := GetNextCharacter(F);
    write(c);
  end;
  readln;
end.