Name

Read Procedure

Syntax

procedure Read(var F: File; var Variable; ...);
procedure Read(var F: TextFile; var Variable; ...);
procedure Read(var Variable; ...);

Description

The Read procedure reads data from a binary or text file. It is not a real procedure.

To read from a typed binary file, the Variable must be of the same type as the base type of the file. Delphi reads one record from the file into Variable and advances the file position in preparation for reading the next record. If the file is untyped, Delphi reads as many bytes as specified for the record size when the file was opened with Reset. You can list more than one variable as arguments to Read, in which case, Read will read multiple records and assign each one to a separate variable.

When reading from a TextFile, Read performs a formatted read. Delphi reads characters from the input file and interprets them according to the type of each Variable. Read skips over white space characters (blanks, tabs, and ends of lines) when reading a number, and stops reading when it gets to another white space character.

When reading strings and characters, Read does not skip over white space. If Variable is a long string, Read reads the entire line into the string, but not the end-of-line characters. If Variable is a short string, Read stops at the end of the line or the size of the string, whichever comes first.

Errors

  • If the file has not been assigned, Read reports I/O error 102.

  • If the file is not open for read access, Read reports I/O error 103.

  • If the input is not formatted correctly (e.g., trying to read 3.14 as an Integer), Read reports I/O error 106.

  • If the read fails for another reason (say, a network error), Read reports the Windows error code as an I/O error.

  • If an input value is out of range for its type (say, 257 when reading a Byte), Read silently casts the value to the correct type without raising an exception or reporting a runtime error.

Tips and Tricks

  • Delphi does not buffer input from a binary file, so you probably want to call BlockRead to read many records at one time.

  • Reading past the end of file raises I/O error 100 for a binary file. For a text file, the read always succeeds in reading the character #26. Reading a number or string results in zero or an empty string.

  • Without a file as the first argument, Read reads from the text file Input.

Example

var
  I: Integer;
  D1, D2: Double;
  S1, S2: string;
begin
  Read(S1); // Reads entire line, but not end of line.
  Read(S2); // Always reads end of line.
  Read(I);  // Skips over end of line and spaces to read a number.
  Read(D1, D2);  // Spaces also terminate and separate numbers.

See Also

BlockRead Procedure, File Keyword, Input Variable, IOResult Function, ReadLn Procedure, TextFile Type, Write Procedure
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset