Opens the file name and returns it with true, or a closed file and false when that fails.
file_open :: (
name: string,
for_writing := false,
keep_existing_content := false,
log_errors := false
) -> (File, bool)
- By default it opens an existing file for reading; a missing file is a failure.
for_writingopens for writing and creates the file when missing; an existing one is cut to nothing, unlesskeep_existing_contentis set, which keeps its bytes and starts at the first one (it does not append: usefile_seek(file, 0, .END)first). Withoutfor_writingthat flag does nothing.
name is UTF-8 and is converted to UTF-16 for the system; text that is not valid UTF-8, an empty name, and a name with a
NUL byte are refused. / and \ both separate directories. Other programs may open, write and delete the file while it is
open. A failure is logged as an error through context.logger only when log_errors is true.
Parameters
- name: string
- for_writing := false
- keep_existing_content := false
- log_errors := false
Returns
- bool
#import "Extensions/Environment";
base := environment_variable("TMPDIR");
if base == "" base = environment_variable("TEMP");
if base == "" base = "/tmp";
path := tprint("%/jai-doc-file-open.txt", base);
defer file_delete(path);
_, found := file_open(path);
assert(!found); // reading needs an existing file
file, ok := file_open(path, for_writing = true);
assert(ok && file_write(*file, "hello"));
file_close(*file);
// Keeping the content starts at the first byte, so this overwrites it.
file, ok = file_open(path, for_writing = true, keep_existing_content = true);
assert(ok && file_write(*file, "J"));
file_close(*file);
text, read_ok := read_entire_file(path);
assert(read_ok && text == "Jello");
free(text);Doesn't run in the browser (only on windows).