RAD Studio (Common)
|
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 |
Description |
Append |
Opens an existing text file for appending. |
AssignFile |
Assigns the name of an external file to a file variable. |
BlockRead |
Reads one or more records from an untyped file. |
BlockWrite |
Writes one or more records into an untyped file. |
ChDir |
Changes the current directory. |
CloseFile |
Closes an open file. |
Eof |
Returns the end-of-file status of a file. |
Eoln |
Returns the end-of-line status of a text file. |
Erase |
Erases an external file. |
FilePos |
Returns the current file position of a typed or untyped file. |
FileSize |
Returns the current size of a file; not used for text files. |
Flush |
Flushes the buffer of an output text file. |
GetDir |
Returns the current directory of a specified drive. |
IOResult |
Returns an integer value that is the status of the last I/O function performed. |
MkDir |
Creates a subdirectory. |
Read |
Reads one or more values from a file into one or more variables. |
Readln |
Does what Read does and then skips to beginning of next line in the text file. |
Rename |
Renames an external file. |
Reset |
Opens an existing file. |
Rewrite |
Creates and opens a new file. |
RmDir |
Removes an empty subdirectory. |
Seek |
Moves the current position of a typed or untyped file to a specified component. Not used with text files. |
SeekEof |
Returns the end-of-file status of a text file. |
SeekEoln |
Returns the end-of-line status of a text file. |
SetTextBuf |
Assigns an I/O buffer to a text file. |
Truncate |
Truncates a typed or untyped file at the current file position. |
Write |
Writes one or more values to a file. |
Writeln |
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.
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, ''); Reset(Input); AssignFile(Output, ''); Rewrite(Output);
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 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); begin with TTextRec(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 product file system at any time.
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.
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.
The following functions are provided for handling null-terminated strings.
Null-terminated string functions
Function |
Description |
StrAlloc |
Allocates a character buffer of a given size on the heap. |
StrBufSize |
Returns the size of a character buffer allocated using StrAlloc or StrNew. |
StrCat |
Concatenates two strings. |
StrComp |
Compares two strings. |
StrCopy |
Copies a string. |
StrDispose |
Disposes a character buffer allocated using StrAlloc or StrNew. |
StrECopy |
Copies a string and returns a pointer to the end of the string. |
StrEnd |
Returns a pointer to the end of a string. |
StrFmt |
Formats one or more values into a string. |
StrIComp |
Compares two strings without case sensitivity. |
StrLCat |
Concatenates two strings with a given maximum length of the resulting string. |
StrLComp |
Compares two strings for a given maximum length. |
StrLCopy |
Copies a string up to a given maximum length. |
StrLen |
Returns the length of a string. |
StrLFmt |
Formats one or more values into a string with a given maximum length. |
StrLIComp |
Compares two strings for a given maximum length without case sensitivity. |
StrLower |
Converts a string to lowercase. |
StrMove |
Moves a block of characters from one string to another. |
StrNew |
Allocates a string on the heap. |
StrPCopy |
Copies a Pascal string to a null-terminated string. |
StrPLCopy |
Copies a Pascal string to a null-terminated string with a given maximum length. |
StrPos |
Returns a pointer to the first occurrence of a given substring within a string. |
StrRScan |
Returns a pointer to the last occurrence of a given character within a string. |
StrScan |
Returns a pointer to the first occurrence of a given character within a string. |
StrUpper |
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.
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 |
Description |
Addr |
Returns a pointer to a specified object. |
AllocMem |
Allocates a memory block and initializes each byte to zero. |
ArcTan |
Calculates the arctangent of the given number. |
Assert |
Raises an exception if the passed expression does not evaluate to true. |
Assigned |
Tests for a nil (unassigned) pointer or procedural variable. |
Beep |
Generates a standard beep. |
Break |
Causes control to exit a for, while, or repeat statement. |
ByteToCharIndex |
Returns the position of the character containing a specified byte in a string. |
Chr |
Returns the character for a specified integer value. |
Close |
Closes a file. |
CompareMem |
Performs a binary comparison of two memory images. |
CompareStr |
Compares strings case sensitively. |
CompareText |
Compares strings by ordinal value and is not case sensitive. |
Continue |
Returns control to the next iteration of for, while, or repeat statements. |
Copy |
Returns a substring of a string or a segment of a dynamic array. |
Cos |
Calculates the cosine of an angle. |
CurrToStr |
Converts a currency variable to a string. |
Date |
Returns the current date. |
DateTimeToStr |
Converts a variable of type TDateTime to a string. |
DateToStr |
Converts a variable of type TDateTime to a string. |
Dec |
Decrements an ordinal variable or a typed pointer variable. |
Dispose |
Releases dynamically allocated variable memory. |
ExceptAddr |
Returns the address at which the current exception was raised. |
Exit |
Exits from the current procedure. |
Exp |
Calculates the exponential of X. |
FillChar |
Fills contiguous bytes with a specified value. |
Finalize |
ninitializes a dynamically allocated variable. |
FloatToStr |
Converts a floating point value to a string. |
FloatToStrF |
Converts a floating point value to a string, using specified format. |
FmtLoadStr |
Returns formatted output using a resourced format string. |
FmtStr |
Assembles a formatted string from a series of arrays. |
Format |
Assembles a string from a format string and a series of arrays. |
FormatDateTime |
Formats a date-and-time value. |
FormatFloat |
Formats a floating point value. |
FreeMem |
Releases allocated memory. |
GetMem |
Allocates dynamic memory and a pointer to the address of the block. |
Halt |
Initiates abnormal termination of a program. |
Hi |
Returns the high-order byte of an expression as an unsigned value. |
High |
Returns the highest value in the range of a type, array, or string. |
Inc |
Increments an ordinal variable or a typed pointer variable. |
Initialize |
Initializes a dynamically allocated variable. |
Insert |
Inserts a substring at a specified point in a string. |
Int |
Returns the integer part of a real number. |
IntToStr |
Converts an integer to a string. |
Length |
Returns the length of a string or array. |
Lo |
Returns the low-order byte of an expression as an unsigned value. |
Low |
Returns the lowest value in the range of a type, array, or string. |
LowerCase |
Converts an ASCII string to lowercase. |
MaxIntValue |
Returns the largest signed value in an integer array. |
MaxValue |
Returns the largest signed value in an array. |
MinIntValue |
Returns the smallest signed value in an integer array. |
MinValue |
Returns smallest signed value in an array. |
New |
Creates a dynamic allocated variable memory and references it with a specified pointer. |
Now |
Returns the current date and time. |
Ord |
Returns the ordinal integer value of an ordinal-type expression. |
Pos |
Returns the index of the first single-byte character of a specified substring in a string. |
Pred |
Returns the predecessor of an ordinal value. |
Ptr |
Converts a value to a pointer. |
Random |
Generates random numbers within a specified range. |
ReallocMem |
Reallocates a dynamically allocatable memory. |
Round |
Returns the value of a real rounded to the nearest whole number. |
SetLength |
Sets the dynamic length of a string variable or array. |
SetString |
Sets the contents and length of the given string. |
ShowException |
Displays an exception message with its address. |
ShowMessage |
Displays a message box with an unformatted string and an OK button. |
ShowMessageFmt |
Displays a message box with a formatted string and an OK button. |
Sin |
Returns the sine of an angle in radians. |
SizeOf |
Returns the number of bytes occupied by a variable or type. |
Sqr |
Returns the square of a number. |
Sqrt |
Returns the square root of a number. |
Str |
Converts an integer or real number into a string. |
StrToCurr |
Converts a string to a currency value. |
StrToDate |
Converts a string to a date format (TDateTime). |
StrToDateTime |
Converts a string to a TDateTime. |
StrToFloat |
Converts a string to a floating-point value. |
StrToInt |
Converts a string to an integer. |
StrToTime |
Converts a string to a time format (TDateTime). |
StrUpper |
Returns an ASCII string in upper case. |
Succ |
Returns the successor of an ordinal value. |
Sum |
Returns the sum of the elements from an array. |
Time |
Returns the current time. |
TimeToStr |
Converts a variable of type TDateTime to a string. |
Trunc |
Truncates a real number to an integer. |
UniqueString |
Ensures that a string has only one reference. (The string may be copied to produce a single reference.) |
UpCase |
Converts a character to uppercase. |
UpperCase |
Returns a string in uppercase. |
VarArrayCreate |
Creates a variant array. |
VarArrayDimCount |
Returns number of dimensions of a variant array. |
VarArrayHighBound |
Returns high bound for a dimension in a variant array. |
VarArrayLock |
Locks a variant array and returns a pointer to the data. |
VarArrayLowBound |
Returns the low bound of a dimension in a variant array. |
VarArrayOf |
Creates and fills a one-dimensional variant array. |
VarArrayRedim |
Resizes a variant array. |
VarArrayRef |
Returns a reference to the passed variant array. |
VarArrayUnlock |
Unlocks a variant array. |
VarAsType |
Converts a variant to specified type. |
VarCast |
Converts a variant to a specified type, storing the result in a variable. |
VarClear |
Clears a variant. |
VarCopy |
Copies a variant. |
VarToStr |
Converts variant to string. |
VarType |
Returns type code of specified variant. |
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|