WRITE - write to file

SYNOPSIS

<WRITE [APPEND] [OUTPUT] [SKIPONFAIL] [FLAGS=$flags] $file>
  ... output to file ...
</WRITE>


DESCRIPTION
The WRITE statement redirects the output generated inside its block to the given $file, truncating if it exists.

The $file argument may also be

  • an empty string - output will to be discarded (i.e. /dev/null or NUL redirect)

  • "-" (single dash) - stdout (i.e. no-op)

  • "--" (two dashes) - top-level stdout (i.e. "break through" all outer <CAPTURE>, <WRITE> etc. and print to output).

  • "---" (three dashes) - prints to stderr; this was added in version 7.01.1394744000 20140313.

If the APPEND flag is given, the file is appended to instead of truncated. The OUTPUT flag acts as it does with <CAPTURE>, i.e. the output of the block is also output normally (ala the Unix tee command), in addition to being redirected to $file.

The SKIPONFAIL flag, when given, causes the code inside the <WRITE> block to be skipped on failure of the $file to be opened, instead of still being executed. This can be used in situations where the block code is entirely optional or redundant if the file-open fails, e.g. it is all logging code: it avoids the overhead of running code whose output will be discarded anyway. On the other hand, the default when SKIPONFAIL is not given - always continue into the block even on file-open failure - ensures potentially critical block code will always be run even if the file cannot be opened, e.g. if a mix of critical and logging code is inside the block.

The FLAGS argument value is a CSV list of zero or more of the other flags. It allows flags to be specified dynamically at run-time if needed.


DIAGNOSTICS
WRITE has no effect on $ret.


EXAMPLE
This function appends a log message ($logmsg) to a log file:

<A NAME=logmsg>
  <WRITE APPEND /tmp/log.txt>
    <fmt "%t %s\n" "now" $logmsg>
  </WRITE>
</A>


CAVEATS
The WRITE statement was added in version 2.1.901600000 19980728. The empty-string, "-" and "--" functionality of $file was added in version 4.00.1004670000 20011101.

The OUTPUT, SKIPONFAIL and FLAGS options were added in version 7. In versions prior to 7, SKIPONFAIL was effectively always on.

While the output of WRITE is buffered, simultaneous writes to the same file by different processes is discouraged, as there is no guarantee any process's data will be completely written before the others'.


SEE ALSO
read, READLN


Copyright © Thunderstone Software     Last updated: Apr 15 2024
Copyright © 2024 Thunderstone Software LLC. All rights reserved.