This chapter discusses text and file I/O and summarizes standard library routines. Many of the procedures and functions listed here are defined in the System unit, which is implicitly compiled with every application. Others are built into the compiler but are treated as if they were in the System unit.
Some standard routines are in units such as SysUtils, which must be listed in a uses clause to make them available in programs. You cannot, however, list System in a uses clause, nor should you modify the System unit or try to rebuild it explicitly.
For more information about the routines listed here, see the online Help.
The table below lists input and output routines.
A file variable is any variable whose type is a file type. There are three classes of file: typed, text, and untyped. The syntax for declaring file types is given in "File types".
Before a file variable can be used, it must be associated with an external file through a call to the AssignFile procedure. An external file is typically a named disk file, but it can also be a device, such as the keyboard or the display. The external file stores the information written to the file or supplies the information read from the file.
Once the association with an external file is established, the file variable must be "opened" to prepare it for input or output. An existing file can be opened via the Reset procedure, and a new file can be created and opened via the Rewrite procedure. Text files opened with Reset are read-only and text files opened with Rewrite and Append are write-only. Typed files and untyped files always allow both reading and writing regardless of whether they were opened with Reset or Rewrite.
Every file is a linear sequence of components, each of which has the component type (or record type) of the file. The components are numbered starting with zero.
Files are normally accessed sequentially. That is, when a component is read using the standard procedure Read or written using the standard procedure Write, the current file position moves to the next numerically ordered file component. Typed files and untyped files can also be accessed randomly through the standard procedure Seek, which moves the current file position to a specified component. The standard functions FilePos and FileSize can be used to determine the current file position and the current file size.
When a program completes processing a file, the file must be closed using the standard procedure CloseFile. After a file is closed, its associated external file is updated. The file variable can then be associated with another external file.
By default, all calls to standard I/O procedures and functions are automatically checked for errors, and if an error occurs an exception is raised (or the program is terminated if exception handling is not enabled). This automatic checking can be turned on and off using the {$I+} and {$I-} compiler directives. When I/O checking is off--that is, when a procedure or function call is compiled in the {$I-} state--an I/O error doesn't cause an exception to be raised; to check the result of an I/O operation, you must call the standard function IOResult instead.
You must call the IOResult function to clear an error, even if you aren't interested in the error. If you don't clear an error and {$I+} is the current state, the next I/O function call will fail with the lingering IOResult error.
This section summarizes I/O using file variables of the standard type Text.
When a text file is opened, the external file is interpreted in a special way: It is considered to represent a sequence of characters formatted into lines, where each line is terminated by an end-of-line marker (a carriage-return character, possibly followed by a linefeed character). The type Text is distinct from the type file of Char.
For text files, there are special forms of Read and Write that let you read and write values that are not of type Char. Such values are automatically translated to and from their character representation. For example, Read(F, I), where I is a type Integer variable, reads a sequence of digits, interprets that sequence as a decimal integer, and stores it in I.
There are two standard text-file variables, Input and Output. The standard file variable Input is a read-only file associated with the operating system's standard input (typically the keyboard). The standard file variable Output is a write-only file associated with the operating system's standard output (typically the display). Before an application begins executing, Input and Output are automatically opened, as if the following statements were executed:
AssignFile(Input, ''); Reset(Input); AssignFile(Output, ''); Rewrite(Output);
Note: Text-oriented I/O is available only in console applications--that is, applications compiled with the "Generate console application" option checked on the Linker page of the Project Options dialog box or with the -cc command-line compiler option. In a GUI (non-console) application, any attempt to read or write using Input or Output will produce an I/O error.
Some of the standard I/O routines that work on text files don't need to have a file variable explicitly given as a parameter. If the file parameter is omitted, Input or Output is assumed by default, depending on whether the procedure or function is input- or output-oriented. For example, Read(X) corresponds to Read(Input, X) and Write(X) corresponds to Write(Output, X).
If you do specify a file when calling one of the input or output routines that work on text files, the file must be associated with an external file using AssignFile, and opened using Reset, Rewrite, or Append. An exception is raised if you pass a file that was opened with Reset to an output-oriented procedure or function. An exception is also raised if you pass a file that was opened with Rewrite or Append to an input-oriented procedure or function.
Untyped files are low-level I/O channels used primarily for direct access to disk files regardless of type and structuring. An untyped file is declared with the word file and nothing more. For example,
var DataFile: file;
For untyped files, the Reset and Rewrite procedures allow an extra parameter to specify the record size used in data transfers. For historical reasons, the default record size is 128 bytes. A record size of 1 is the only value that correctly reflects the exact size of any file. (No partial records are possible when the record size is 1.)
Except for Read and Write, all typed-file standard procedures and functions are also allowed on untyped files. Instead of Read and Write, two procedures called BlockRead and BlockWrite are used for high-speed data transfers.
You can define your own text-file device drivers for your Windows programs. A text-file device driver is a set of four functions that completely implement an interface between Object Pascal's file system and some device.
The four functions that define each device driver are Open, InOut, Flush, and Close. The function header of each function is
functionDeviceFunc(var F: TTextRec): Integer;
where DeviceFunc is the name of the function (that is, Open, InOut, Flush, or Close). For information about the TTextRec type, see the online Help. The return value of a device-interface function becomes the value returned by IOResult. If the return value is zero, the operation was successful.
To associate the device-interface functions with a specific file, you must write a customized Assign procedure. The Assign procedure must assign the addresses of the four device-interface functions to the four function pointers in the text-file variable. In addition, it should store the fmClosed "magic" constant in the Mode field, store the size of the text-file buffer in BufSize, store a pointer to the text-file buffer in BufPtr, and clear the Name string.
Assuming, for example, that the four device-interface functions are called DevOpen, DevInOut, DevFlush, and DevClose, the Assign procedure might look like this:
procedure AssignDev(var F: Text);
begin
with TextRec(F) do
begin
Mode := fmClosed;
BufSize := SizeOf(Buffer);
BufPtr := @Buffer;
OpenFunc := @DevOpen;
InOutFunc := @DevInOut;
FlushFunc := @DevFlush;
CloseFunc := @DevClose;
Name[0] := #0;
end;
end;
The device-interface functions can use the UserData field in the file record to store private information. This field isn't modified by the Delphi file system at any time.
The functions that make up a text-file device driver are described below.
The Open function is called by the Reset, Rewrite, and Append standard procedures to open a text file associated with a device. On entry, the Mode field contains fmInput, fmOutput, or fmInOut to indicate whether the Open function was called from Reset, Rewrite, or Append.
The Open function prepares the file for input or output, according to the Mode value. If Mode specified fmInOut (indicating that Open was called from Append), it must be changed to fmOutput before Open returns.
Open is always called before any of the other device-interface functions. For that reason, AssignDev only initializes the OpenFunc field, leaving initialization of the remaining vectors up to Open. Based on Mode, Open can then install pointers to either input- or output-oriented functions. This saves the InOut, Flush functions and the CloseFile procedure from determining the current mode.
The InOut function is called by the Read, Readln, Write, Writeln, Eof, Eoln, SeekEof, SeekEoln, and CloseFile standard routines whenever input or output from the device is required.
When Mode is fmInput, the InOut function reads up to BufSize characters into BufPtr^, and returns the number of characters read in BufEnd. In addition, it stores zero in BufPos. If the InOut function returns zero in BufEnd as a result of an input request, Eof becomes True for the file.
When Mode is fmOutput, the InOut function writes BufPos characters from BufPtr^, and returns zero in BufPos.
The Flush function is called at the end of each Read, Readln, Write, and Writeln. It can optionally flush the text-file buffer.
If Mode is fmInput, the Flush function can store zero in BufPos and BufEnd to flush the remaining (unread) characters in the buffer. This feature is seldom used.
If Mode is fmOutput, the Flush function can write the contents of the buffer exactly like the InOut function, which ensures that text written to the device appears on the device immediately. If Flush does nothing, the text doesn't appear on the device until the buffer becomes full or the file is closed.
The Close function is called by the CloseFile standard procedure to close a text file associated with a device. (The Reset, Rewrite, and Append procedures also call Close if the file they are opening is already open.) If Mode is fmOutput, then before calling Close, the file system calls the InOut function to ensure that all characters have been written to the device.
Object Pascal's extended syntax allows the Read, Readln, Str, and Val standard procedures to be applied to zero-based character arrays, and allows the Write, Writeln, Val, AssignFile, and Rename standard procedures to be applied to both zero-based character arrays and character pointers. In addition, the following functions are provided for handling null-terminated strings. For more information about null-terminated strings, see "Working with null-terminated strings".
Standard string-handling functions have multibyte-enabled counterparts that also implement locale-specific ordering for characters. Names of multibyte functions start with Ansi-. For example, the multibyte version of StrPos is AnsiStrPos. Multibyte character support is operating-system dependent and based on the current Windows locale.
The System unit provides three functions, WideCharToString, WideCharLenToString, and StringToWideChar, that can be used to convert null-terminated wide character strings to single- or double-byte long strings.
For more information about wide-character strings, see "About extended character sets".
The table below lists frequently used procedures and functions found in Delphi's libraries. This is not an exhaustive inventory of standard routines. For more information about these and other routines, see the online Help.
For information on format strings, see "Format strings" in the online Help.
pubsweb@inprise.com
Copyright © 1999, Inprise Corporation. All rights reserved.