Sign in Join
FPDoc Onlineexperiment

ReadFileToString function

In unit FileUtil

Returns a string with the contents of the specified file.

Declaration

pascal
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 is a String function used to read the content from the specified Filename and return its contents in 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). Use ExpandFileName(), ExpandFileNameUTF8(), or CleanAndExpandFilename() to resolve a path which includes '~' notation. 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. 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.

For platforms which do not support 64-bit operations, a FileSize value larger than MaxLongInt is invalid. In this case, ReadFileToString silently exits with an empty string ('') in the return value.

ReadFileToString creates a temporary TFileStream instance used to read the content from the specified Filename. For FPC version 3.3.1 or higher, the Read64 method in the stream is used to read the file content in a single pass. For FPC versions prior to 3.3.1, the Read method is called repeatedly using MaxLongInt-sized chunks until all of the content has been read into the return value.

An exception raised in the routine is caught and ignored. In this case the return value is an empty string ('').

Use ReadFileToBytes to get the contents of a file as an array of byte values.

Modified in LazUtils version 4.3 to handle file sizes larger than 2GB in FPC version prior to 3.3.1.

See also

An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.