File module

read_entire_file

procedure · 2 overloadsSource

Reads the rest of an open file, from its current position to its end, into a new string.

read_entire_file :: (f: File, zero_terminated := false) -> (string, bool)

Returns ("", false) when the position or length cannot be read, the position is past the end, memory runs out, or the read fails. With zero_terminated, one extra 0 byte follows the text and is not counted in count, so the result can go to C. The string comes from context.allocator and the caller frees it; the file stays open, at its end.

Parameters

f: File
zero_terminated := false

Returns

string
bool
ExampleOpen in playground ↗
#import "Extensions/Environment";
base := environment_variable("TMPDIR");
if base == "" base = environment_variable("TEMP");
if base == "" base = "/tmp";
path := tprint("%/jai-doc-read-rest.bin", base);
defer file_delete(path);

assert(write_entire_file(path, "abcdef"));
file, ok := file_open(path);
assert(ok);
defer file_close(*file);

assert(file_set_position(file, 2));
rest, read_ok := read_entire_file(file, zero_terminated = true);
assert(read_ok && rest == "cdef" && rest.data[rest.count] == 0);
free(rest);
read_entire_file :: (
    name: string,
    zero_terminated := false,
    log_errors := false
) -> (string, bool)

Reads the whole file name into a new string. Returns ("", false) when it cannot be opened or read.

The string comes from context.allocator and the caller frees it, also for an empty file, which gives an empty string with true. The content is bytes: it may hold 0, line endings are not translated, and it is not checked for UTF-8. zero_terminated adds an uncounted 0 byte after the text. When the file cannot be opened, Nothing is printed for a missing file: the result says so. log_errors = true reports it through context.logger.

Parameters

name: string
zero_terminated := false
log_errors := false

Returns

string
bool
ExampleOpen in playground ↗
#import "Extensions/Environment";
base := environment_variable("TMPDIR");
if base == "" base = environment_variable("TEMP");
if base == "" base = "/tmp";
path := tprint("%/jai-doc-read-entire.txt", base);
defer file_delete(path);

_, found := read_entire_file(path);
assert(!found);

assert(write_entire_file(path, "one\r\ntwo\0"));
text, ok := read_entire_file(path);
assert(ok && text.count == 9 && text[8] == 0);
free(text);

See also