RAD Studio (Common)
Standard Routines and I/O

These topics discuss text and file I/O and summarize standard library routines. Many of the procedures and functions listed here are defined in the System and SysInit units, which are implicitly used 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.

The table below lists input and output routines.  

Input and output procedures and functions  

Procedure or function  
Opens an existing text file for appending.  
Assigns the name of an external file to a file variable.  
Reads one or more records from an untyped file.  
Writes one or more records into an untyped file.  
Changes the current directory.  
Closes an open file.  
Returns the end-of-file status of a file.  
Returns the end-of-line status of a text file.  
Erases an external file.  
Returns the current file position of a typed or untyped file.  
Returns the current size of a file; not used for text files.  
Flushes the buffer of an output text file.  
Returns the current directory of a specified drive.  
Returns an integer value that is the status of the last I/O function performed.  
Creates a subdirectory.  
Reads one or more values from a file into one or more variables.  
Does what Read does and then skips to beginning of next line in the text file.  
Renames an external file.  
Opens an existing file.  
Creates and opens a new file.  
Removes an empty subdirectory.  
Moves the current position of a typed or untyped file to a specified component. Not used with text files.  
Returns the end-of-file status of a text file.  
Returns the end-of-line status of a text file.  
Assigns an I/O buffer to a text file.  
Truncates a typed or untyped file at the current file position.  
Writes one or more values to a file.  
Does the same as Write, and then writes an end-of-line marker to the text file.  

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. Note that file types are only available on the Win32 platform. 

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.

Text Files

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 line feed 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, '');
AssignFile(Output, '');

Note: For Win32 applications, 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 error occurs if you pass a file that was opened with Reset to an output-oriented procedure or function. An error also occurs if you pass a file that was opened with Rewrite or Append to an input-oriented procedure or function.

Untyped Files

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 programs. A text file device driver is a set of four functions that completely implement an interface between Delphi'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

function DeviceFunc(var F: TTextRec): Integer;

where DeviceFunc is the name of the function (that is, Open, InOut, Flush, or Close). 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 fmClosedmagic 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);
   with TTextRec(F) do
    Mode := fmClosed;
    BufSize := SizeOf(Buffer);
    BufPtr := @Buffer;
    OpenFunc := @DevOpen;
    InOutFunc := @DevInOut;
    FlushFunc := @DevFlush;
    CloseFunc := @DevClose;
    Name[0] := #0;

The device-interface functions can use the UserData field in the file record to store private information. This field isn't modified by the product file system at any time.

The Open function

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

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

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

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.

The Delphi language'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.

Null-Terminated String Functions

The following functions are provided for handling null-terminated strings.  

Null-terminated string functions  

Allocates a character buffer of a given size on the heap.  
Returns the size of a character buffer allocated using StrAlloc or StrNew.  
Concatenates two strings.  
Compares two strings.  
Copies a string.  
Disposes a character buffer allocated using StrAlloc or StrNew.  
Copies a string and returns a pointer to the end of the string.  
Returns a pointer to the end of a string.  
Formats one or more values into a string.  
Compares two strings without case sensitivity.  
Concatenates two strings with a given maximum length of the resulting string.  
Compares two strings for a given maximum length.  
Copies a string up to a given maximum length.  
Returns the length of a string.  
Formats one or more values into a string with a given maximum length.  
Compares two strings for a given maximum length without case sensitivity.  
Converts a string to lowercase.  
Moves a block of characters from one string to another.  
Allocates a string on the heap.  
Copies a Pascal string to a null-terminated string.  
Copies a Pascal string to a null-terminated string with a given maximum length.  
Returns a pointer to the first occurrence of a given substring within a string.  
Returns a pointer to the last occurrence of a given character within a string.  
Returns a pointer to the first occurrence of a given character within a string.  
Converts a string to uppercase.  

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 locale.

Wide-Character Strings

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. 

Assignment will also convert between strings. For instance, the following are both valid:

MyAnsiString := MyWideString;
     MyWideString := MyAnsiString;

The table below lists frequently used procedures and functions found in CodeGear product libraries. This is not an exhaustive inventory of standard routines.  

Other standard routines  

Procedure or function  
Returns a pointer to a specified object.  
Allocates a memory block and initializes each byte to zero.  
Calculates the arctangent of the given number.  
Raises an exception if the passed expression does not evaluate to true.  
Tests for a nil (unassigned) pointer or procedural variable.  
Generates a standard beep.  
Causes control to exit a for, while, or repeat statement.  
Returns the position of the character containing a specified byte in a string.  
Returns the character for a specified integer value.  
Closes a file.  
Performs a binary comparison of two memory images.  
Compares strings case sensitively.  
Compares strings by ordinal value and is not case sensitive.  
Returns control to the next iteration of for, while, or repeat statements.  
Returns a substring of a string or a segment of a dynamic array.  
Calculates the cosine of an angle.  
Converts a currency variable to a string.  
Returns the current date.  
Converts a variable of type TDateTime to a string.  
Converts a variable of type TDateTime to a string.  
Decrements an ordinal variable or a typed pointer variable.  
Releases dynamically allocated variable memory.  
Returns the address at which the current exception was raised.  
Exits from the current procedure.  
Calculates the exponential of X.  
Fills contiguous bytes with a specified value.  
ninitializes a dynamically allocated variable.  
Converts a floating point value to a string.  
Converts a floating point value to a string, using specified format.  
Returns formatted output using a resourced format string.  
Assembles a formatted string from a series of arrays.  
Assembles a string from a format string and a series of arrays.  
Formats a date-and-time value.  
Formats a floating point value.  
Releases allocated memory.  
Allocates dynamic memory and a pointer to the address of the block.  
Initiates abnormal termination of a program.  
Returns the high-order byte of an expression as an unsigned value.  
Returns the highest value in the range of a type, array, or string.  
Increments an ordinal variable or a typed pointer variable.  
Initializes a dynamically allocated variable.  
Inserts a substring at a specified point in a string.  
Returns the integer part of a real number.  
Converts an integer to a string.  
Returns the length of a string or array.  
Returns the low-order byte of an expression as an unsigned value.  
Returns the lowest value in the range of a type, array, or string.  
Converts an ASCII string to lowercase.  
Returns the largest signed value in an integer array.  
Returns the largest signed value in an array.  
Returns the smallest signed value in an integer array.  
Returns smallest signed value in an array.  
Creates a dynamic allocated variable memory and references it with a specified pointer.  
Returns the current date and time.  
Returns the ordinal integer value of an ordinal-type expression.  
Returns the index of the first single-byte character of a specified substring in a string.  
Returns the predecessor of an ordinal value.  
Converts a value to a pointer.  
Generates random numbers within a specified range.  
Reallocates a dynamically allocatable memory.  
Returns the value of a real rounded to the nearest whole number.  
Sets the dynamic length of a string variable or array.  
Sets the contents and length of the given string.  
Displays an exception message with its address.  
Displays a message box with an unformatted string and an OK button.  
Displays a message box with a formatted string and an OK button.  
Returns the sine of an angle in radians.  
Returns the number of bytes occupied by a variable or type.  
Returns the square of a number.  
Returns the square root of a number.  
Converts an integer or real number into a string.  
Converts a string to a currency value.  
Converts a string to a date format (TDateTime).  
Converts a string to a TDateTime.  
Converts a string to a floating-point value.  
Converts a string to an integer.  
Converts a string to a time format (TDateTime).  
Returns an ASCII string in upper case.  
Returns the successor of an ordinal value.  
Returns the sum of the elements from an array.  
Returns the current time.  
Converts a variable of type TDateTime to a string.  
Truncates a real number to an integer.  
Ensures that a string has only one reference. (The string may be copied to produce a single reference.)  
Converts a character to uppercase.  
Returns a string in uppercase.  
Creates a variant array.  
Returns number of dimensions of a variant array.  
Returns high bound for a dimension in a variant array.  
Locks a variant array and returns a pointer to the data.  
Returns the low bound of a dimension in a variant array.  
Creates and fills a one-dimensional variant array.  
Resizes a variant array.  
Returns a reference to the passed variant array.  
Unlocks a variant array.  
Converts a variant to specified type.  
Converts a variant to a specified type, storing the result in a variable.  
Clears a variant.  
Copies a variant.  
Converts variant to string.  
Returns type code of specified variant.  
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!