Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi File Access - Why do I get an incomplete output if I don't close my file?

Following is a simple console application then generates ten sets of 3 random numbers and prints them out to both the console window and a text file, 'Output.txt'.

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;
var
  outputFile: TextFile;
  i: Integer;
  a,b,c: Single;
begin
  try
    Randomize;
    AssignFile(outputFile, 'Output.txt');
    ReWrite(outputFile);
    for i := 0 to 9 do
    begin
      a := Random;
      b := Random;
      c := Random;
      WriteLn(FloatToStr(a) + Char(9) + FloatToStr(b) + Char(9) + FloatToStr(c));
      WriteLn(outputFile, FloatToStr(a) + Char(9) + FloatToStr(b) + Char(9) + FloatToStr(c));
    end;
    Close(outputFile);
    Sleep(10000);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

The text file holds the same information as the console window only if I include line 26:

Close(outputFile);

If I omit this from the code I would expect to get the same data printed to the text file anyway but what is actually printed in the text file is the same for the first 9 lines and then an incomplete final line.

Why does this happen? By what process does the final line only get written in part due to the omission of the Close procedure?

like image 361
Trojanian Avatar asked Dec 20 '22 10:12

Trojanian


1 Answers

This is caused because the file output is buffered. When you close the file it causes the buffer to be flushed and the remaining content put out to disk.

An alternative is to perform a Flush(outputFile) after the WriteLn for the file, it will accomplish the same thing, but at the expense of performance.

like image 142
Petesh Avatar answered Dec 24 '22 02:12

Petesh