[Overview][Constants][Types][Classes][Procedures and functions][Index] Reference for unit 'FileUtil' (#lazutils)

ReadFileToString

Returns a string with the contents of the named text file.

Declaration

Source position: fileutil.pas line 71

function ReadFileToString(

  const Filename: string

):string;

Arguments

Filename

  

The qualified name for the file read in the routine.

Function result

The contents of the file as a string. Returns an empty string if there is an error, the file does not exist, or the file is empty.

Description

ReadFileToString opens the file specified in the FileName argument, then reads its contents into the Result string.

FileName can include a path to the file, but cannot include a value which needs to be resolved (like '~' for the home directory on UNIX-like file systems). Relative path notation can be used in FileName.

ReadFileToString does not check whether FileName contains an expanded value or whether it exists on the local file system. It does not complain if the file does not exist or cannot be accessed; the return value is an empty string ('') for these conditions. ExpandFileName() or ExpandFileNameUTF8() can be used to resolve a path with '~' notation. FileExists() or FileExistsUTF8() can be used to verify whether the file path/name exists before ReadFileToString is called.

FileSize is used to determine the storage size needed for the return value. UNIX-like file systems usually return 0 as the file size if FileName is located on a virtual file system (like /proc). In this case, the return value is an empty string. Another mechanism (like TStringList.LoadfromFile) should be used for virtual files.

FileOpenUTF8 is called to get a shared handle used to read from (but not write to) the specified file name. If an invalid handle is returned, the routine quietly exits with an empty return value.

FileRead is called for the handle to read the number of bytes in the file size into the return value.

FileClose is called to close the handle for the file when the operation has been completed.

Errors

If an error occurs while reading from or closing the file handle, the Exception is handled in the routine and an empty string is returned.

See also

FileSize

  

Gets the size for the specified file name.

FileOpenUTF8

  

Opens the specified file name and returns its file handle.

FileExistsUTF8

  

Indicates if the specified UTF-8-encoded file name exists.

ExpandFileNameUTF8

  

Expands the values in FileName and BaseDir to an absolute file name.

FileRead

FileClose

FileExists

feInvalidHandle


Version 4.0 Generated 2025-05-03 Home