File module

write_entire_file

procedure · 3 overloadsSource

Replaces the file name with data: it is created if missing and cut to nothing otherwise. Returns false when it cannot be opened, written or flushed.

write_entire_file :: (name: string, data: string) -> bool

On failure the file may be left empty or partly written; the old content is not kept. The name is a path in UTF-8. To change a file without ever exposing a partial result, write a second file and file_move it into place.

Parameters

name: string
data: string

Returns

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-write-entire.txt", base);
defer file_delete(path);

assert(write_entire_file(path, "a long first version"));
assert(write_entire_file(path, "short"));
text, ok := read_entire_file(path);
assert(ok && text == "short");
free(text);
assert(!write_entire_file(tprint("%/jai-doc-no-such-dir/file", base), "x"));
write_entire_file :: (name: string, data: *void, count: int) -> bool

Replaces the file name with count bytes at data, as the string form does. A count of 0 empties the file; data may then be null. A negative count, or null data with a positive count, fails without writing.

Parameters

name: string
data: *void
count: int

Returns

bool
write_entire_file :: (
    name: string,
    builder: *String_Builder,
    do_reset := true
) -> bool

Replaces the file name with the content of builder, then resets the builder unless do_reset is false.

The builder is reset even when the file cannot be opened or written, so the text is gone after a failure.

Parameters

name: string
builder: *String_Builder
do_reset := true

Returns

bool

See also