Basic Turbo Delphi I/O Functions

System File I/O
AppendOpens an existing text file for appending.
AssignFileAssigns the name of an external file to a file variable.
BlockReadReads one or more records from an untyped file.
BlockWriteWrites one or more records into an untyped file.
ChDirChanges the current directory.
CloseFileCloses an open file.
EofReturns the end-of-file status of a file.
EolnReturns the end-of-line status of a text file.
EraseErases an external file.
FilePosReturns the current file position of a typed or untyped file.
FileSizeReturns the current size of a file; not used for text files.
FlushFlushes the buffer of an output text file.
GetDirReturns the current directory of a specified drive.
IOResultReturns an integer value that is the status of the last I/O function performed.
MkDirCreates a subdirectory.
ReadReads one or more values from a file into one or more variables.
ReadlnDoes what Read does and then skips to beginning of next line in the text file.
RenameRenames an external file.
ResetOpens an existing file.
RewriteCreates and opens a new file.
RmDirRemoves an empty subdirectory.
SeekMoves the current position of a typed or untyped file to a specified component. Not used with text files.
SeekEofReturns the end-of-file status of a text file.
SeekEolnReturns the end-of-line status of a text file.
SetTextBufAssigns an I/O buffer to a text file.
TruncateTruncates a typed or untyped file at the current file position.
WriteWrites one or more values to a file.
WritelnDoes the same as Write, and then writes an end-of-line marker to the text file.

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.

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 .

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.

File I/O Using Handles: FileOpen Routine

Opens a specified file using a specified access mode.

  function FileOpen(const FileName: string; Mode: Cardinal): Integer;


  • to_read


Use FileOpen to open a file and obtain a file handle. The access mode value is constructed by or-ing one of the fmOpen constants with one of the fmShare constants defined in File open mode constants. If the return value is 0 or greater, the function was successful and the value is the file handle of the opened file. A return value of -1 indicates that an error occurred.

  inf_hand : integer; {handle for the file}

      inf_hand := fileopen(CookieFileName,to_read);
      if inf_hand = -1
        {if the handle comes back -1, it didn't work}
        then begin
          bombout('Couldn''t read fortune.');
        end {then}
        else begin
          endptr := fileseek(inf_hand,0,frombottom); {find EOF}
          if locptr >= endptr
            then get_new_fortune_file;
          if IOresult <> 0
            then bombout('Fileseek failed.');

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.

LF is optional.

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.

Read Routine

Read reads data from a file.

[Delphi] procedure Read(var F: file; V1: Pointer [; V2; …; Vn]);


The Read procedure can be used in Delphi code in the following ways.

For typed files, it reads a file component into a variable.

For text files, it reads one or more values into one or more variables.

Read reads all characters up to, but not including, the next end-of-line marker or until Eof(F) becomes true; it does not skip to the next line after reading. If the resulting string is longer than the maximum length of the string variable, it is truncated.

After the first Read, each subsequent Read sees the end-of-line marker and returns a zero-length string.

Use multiple Readln calls to read successive string values.

When the extended syntax is enabled, Read can read null-terminated strings into zero-based character arrays.

Read reads one character from the file and assigns it to the variable. If CRLF mode is enabled and Eof(F) was true before Read was executed, the value Chr(26) (a Ctrl-Z character) is assigned to the variable. (To enable CRLF mode, use SetLineBreakStyle.)

Read skips any blanks, tabs, or end-of-line markers preceding the numeric string.

If the numeric string does not conform to the expected format, an I/O error occurs; otherwise, the value is assigned to the variable.

The next Read starts with the blank, tab, or end-of-line marker that terminated the numeric string.

Related Information


Handling null-Terminated Strings

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.

Procedures and Functions in SysUtils:
StrAllocAllocates a character buffer of a given size on the heap.
StrBufSizeReturns the size of a character buffer allocated using StrAlloc or StrNew.
StrCatConcatenates two strings.
StrCompCompares two strings.
StrCopyCopies a string.
StrDisposeDisposes a character buffer allocated using StrAlloc or StrNew.
StrECopyCopies a string and returns a pointer to the end of the string.
StrEndReturns a pointer to the end of a string.
StrFmtFormats one or more values into a string.
StrICompCompares two strings without case sensitivity.
StrLCatConcatenates two strings with a given maximum length of the resulting string.
StrLCompCompares two strings for a given maximum length.
StrLCopyCopies a string up to a given maximum length.
StrLenReturns the length of a string.
StrLFmtFormats one or more values into a string with a given maximum length.
StrLICompCompares two strings for a given maximum length without case sensitivity.
StrLowerConverts a string to lowercase.
StrMoveMoves a block of characters from one string to another.
StrNewAllocates a string on the heap.
StrPCopyCopies a Pascal string to a null-terminated string.
StrPLCopyCopies a Pascal string to a null-terminated string with a given maximum length.
StrPosReturns a pointer to the first occurrence of a given substring within a string.
StrRScanReturns a pointer to the last occurrence of a given character within a string.
StrScanReturns a pointer to the first occurrence of a given character within a string.
StrUpperConverts 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;

Other Standard Routines

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

AddrReturns a pointer to a specified object.
AllocMemAllocates a memory block and initializes each byte to zero.
ArcTanCalculates the arctangent of the given number.
AssertRaises an exception if the passed expression does not evaluate to true.
AssignedTests for a nil (unassigned) pointer or procedural variable.
BeepGenerates a standard beep.
BreakCauses control to exit a for, while, or repeat statement.
ByteToCharIndexReturns the position of the character containing a specified byte in a string.
ChrReturns the character for a specified integer value.
CloseCloses a file.
CompareMemPerforms a binary comparison of two memory images.
CompareStrCompares strings case sensitively.
CompareTextCompares strings by ordinal value and is not case sensitive.
ContinueReturns control to the next iteration of for, while, or repeat statements.
CopyReturns a substring of a string or a segment of a dynamic array.
CosCalculates the cosine of an angle.
CurrToStrConverts a currency variable to a string.
DateReturns the current date.
DateTimeToStrConverts a variable of type TDateTime to a string.
DateToStrConverts a variable of type TDateTime to a string.
DecDecrements an ordinal variable or a typed pointer variable.
DisposeReleases dynamically allocated variable memory.
ExceptAddrReturns the address at which the current exception was raised.
ExitExits from the current procedure.
ExpCalculates the exponential of X.
FillCharFills contiguous bytes with a specified value.
Finalizeninitializes a dynamically allocated variable.
FloatToStrConverts a floating point value to a string.
FloatToStrFConverts a floating point value to a string, using specified format.
FmtLoadStrReturns formatted output using a resourced format string.
FmtStrAssembles a formatted string from a series of arrays.
FormatAssembles a string from a format string and a series of arrays.
FormatDateTimeFormats a date-and-time value.
FormatFloatFormats a floating point value.
FreeMemReleases allocated memory.
GetMemAllocates dynamic memory and a pointer to the address of the block.
HaltInitiates abnormal termination of a program.
HiReturns the high-order byte of an expression as an unsigned value.
HighReturns the highest value in the range of a type, array, or string.
IncIncrements an ordinal variable or a typed pointer variable.
InitializeInitializes a dynamically allocated variable.
InsertInserts a substring at a specified point in a string.
IntReturns the integer part of a real number.
IntToStrConverts an integer to a string.
LengthReturns the length of a string or array.
LoReturns the low-order byte of an expression as an unsigned value.
LowReturns the lowest value in the range of a type, array, or string.
LowerCaseConverts an ASCII string to lowercase.
Math.MaxIntValueReturns the largest signed value in an integer array.
Math.MaxValueReturns the largest signed value in an array.
Math.MinIntValueReturns the smallest signed value in an integer array.
Math.MinValueReturns smallest signed value in an array.
NewCreates a dynamic allocated variable memory and references it with a specified pointer.
NowReturns the current date and time.
OrdReturns the ordinal integer value of an ordinal-type expression.
PosReturns the index of the first single-byte character of a specified substring in a string.
PredReturns the predecessor of an ordinal value.
PtrConverts a value to a pointer.
RandomGenerates random numbers within a specified range.
ReallocMemReallocates a dynamically allocatable memory.
RoundReturns the value of a real rounded to the nearest whole number.
SetLengthSets the dynamic length of a string variable or array.
SetStringSets the contents and length of the given string.
SinReturns the sine of an angle in radians.
SizeOfReturns the number of bytes occupied by a variable or type.
SqrReturns the square of a number.
SqrtReturns the square root of a number.
StrConverts an integer or real number into a string.
StrToCurrConverts a string to a currency value.
StrToDateConverts a string to a date format (TDateTime).
StrToDateTimeConverts a string to a TDateTime.
StrToFloatConverts a string to a floating-point value.
StrToIntConverts a string to an integer.
StrToTimeConverts a string to a time format (TDateTime).
StrUpperReturns an ASCII string in upper case.
SuccReturns the successor of an ordinal value.
Math.SumReturns the sum of the elements from an array.
TimeReturns the current time.
TimeToStrConverts a variable of type TDateTime to a string.
TruncTruncates a real number to an integer.
UniqueStringEnsures that a string has only one reference. (The string may be copied to produce a single reference.)
UpCaseConverts a character to uppercase.
UpperCaseReturns a string in uppercase.
Variants.VarArrayCreateCreates a variant array.
Variants.VarArrayDimCountReturns number of dimensions of a variant array.
Variants.VarArrayHighBoundReturns high bound for a dimension in a variant array.
Variants.VarArrayLockLocks a variant array and returns a pointer to the data.
Variants.VarArrayLowBoundReturns the low bound of a dimension in a variant array.
Variants.VarArrayOfCreates and fills a one-dimensional variant array.
VarArrayRedimResizes a variant array.
Variants.VarArrayRefReturns a reference to the passed variant array.
Variants.VarArrayUnlockUnlocks a variant array.
Variants.VarAsTypeConverts a variant to specified type.
VarCastConverts a variant to a specified type, storing the result in a variable.
VarClearClears a variant.
VarCopyCopies a variant.
Variants.VarToStrConverts variant to string.
Variants.VarTypeReturns type code of specified variant.

Show Message

Dialogs.ShowMessageDisplays a message box with an unformatted string and an OK button.
Dialogs.ShowMessageFmtDisplays a message box with a formatted string and an OK button.

Extracting info from paths

blog/delphi_summary.txt · Last modified: 2017/07/13 20:33 (external edit)
Recent changes RSS feed Creative Commons License Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki