ReadFileToBytes function
Returns a TBytes value with the contents of the specified file.
Declaration
function ReadFileToBytes(const Filename: string): TBytesArguments
Filename | The qualified name for the file read in the routine. |
Function result
TBytes value with the contents of the file, or an empty array if the file does not exist or an error occurs.
Description
ReadFileToBytes is a
TBytes function used to read and
return the content from the specified file.
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.
ReadFileToBytes 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 array for these conditions. FileExists() or FileExistsUTF8() can be used to verify whether the file path/name exists before ReadFileToBytes 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 array. 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, ReadFileToBytes silently exits with an empty array 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 array.
Use ReadFileToString to get the contents of a file as a string value.
Added in LazUtils version 4.3.
See also
An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.
