FWRITE

The FWRITE function is used to write data to a file, either integer values in bits or string values in bytes.

  • Integers may be of any bit width and will be written in little endian format. Integer values are packed together as they're written; they are not padded to byte boundaries.
  • Strings are written in UTF-8 encoding and are byte aligned.

Syntax

FWRITE( FILE fileHandle, INT value )
FWRITE( FILE fileHandle, STRING value )

Parameters

fileHandle
The file handle to write to.
value
Either an INT or STRING value to write to the file.

Errors

If the write fails, then the FERROR flag will be set. Possible reasons that the function might fail and FERROR be set include:

  • The file was not opened in a mode that allows writing.
  • It has been locked.
  • It has been deleted.
  • It is no longer available, perhaps because it's on a network share and that has become unreachable.

Alignment

The current position in the file is measured in bits. Integers are written whatever the current alignment is, packing them together. Before a string is written, if necessary, the file is padded with zeroes to align to a byte boundary - this can only occur when writing an integer whose width is not a multiple of 8 followed by a string.

Since the underlying file on disk can only contain whole bytes, the file is padded with zeroes to align it to the next byte boundary when it is closed.

Example

LOCAL WriteIncrementingNumbers(FILE fileHandle)()
  INT counter WIDTH 32;

  FOR counter := 0 FOR 1024
    FWRITE(fileHandle, counter);
  END;

  FCLOSE(fileHandle);
END;

The resulting file will be 4KB in size and contain 32bit incrementing values. If no width was specified in the declaration of counter, then the variable would start out as 1 bit and grow as needed as it was incremented; the resulting file in this case would be substantially smaller.

Any output file will be little endian. Example:

LOCAL WriteFile(FILE fileHandle)()
  INT a WIDTH 32 := 0x12345678;
  INT b WIDTH 16 := 0xabcd;
  INT c WIDTH 8  := 0x1;
  INT d WIDTH 4  := 0xf;

  FWRITE(fileHandle, a);
  FWRITE(fileHandle, b);
  FWRITE(fileHandle, c);
  FWRITE(fileHandle, d);
END;

The file will contain the following byte sequence:

0x78 0x56 0x34 0x12 0xcd 0xab 0x01 0x0f

See also