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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With