read_file

Definition: include builtins/read_file.e
object o = read_file(object file, integer as_text = BINARY_MODE)
Description: Return the contents of a file as a single string (sequence of bytes), or -1 if the file cannot be opened.

file: an object, either a file path or the handle to an open file.
as_text: integer, BINARY_MODE (the default) assumes binary mode that causes every byte to be read in, whereas TEXT_MODE assumes text mode that ensures lines end with just a Ctrl-J (NewLine) character, with the first byte value of 26 (Ctrl-Z) interpreted as end-of-file.
Comments: When using BINARY_MODE, each byte in the file is returned as an element in the return sequence.
When not using BINARY_MODE, the file will be interpreted as a text file. This means that all line endings will be transformed to a single 0x0A character and the first 0x1A character (Ctrl-Z) will indicate the end of file (all data after this will not be returned to the caller.)

As this is a simple compatibility shim for OpenEuphoria, the constants BINARY_MODE and TEXT_MODE are declared in builtins/read_file.e, rather than psym.e, and cannot be used before the include statement.

The file parameter can be a string, in which case the file is opened and closed by this routine, or an integer from a previous call to open(), in which case it is not closed by this routine.

If the file cannot be opened, -1 is returned.
Example 1:
data = read_file("my_file.txt")
-- data contains the entire contents of my_file.txt
Example 2:
fh = open("my_file.txt", "r")
data = read_file(fh)
close(fh)
-- data contains the entire contents of my_file.txt
Example 3:
{} = system_exec("dir > lsoutput",4) 
object results = read_file("lsoutput",TEXT_MODE) 
puts(1,results)
See Also: read_lines, system_exec