FGETI

The FGETI function is used to read a number of bits from a file. In XJEase, files are considered to be streams of bits and not bytes. Therefore, the current file position is measured in bits. Reading an integer always reads the appropriate number of bits without any heed to byte boundaries in the file.

Syntax

FGETI( FILE fileHandle, INT bitCount )

Parameters

fileHandle
The file handle to read from.
bitCount
The number of bits to read from the file.

Return value

An INT value containing the next bits from the file. If there are not enough bits left in the file to satisfy the read, then the available bits are returned and the FEOF flag is set.

Errors

If the read fails, then either the FEOF or 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 reading.
  • 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.

Example

LOCAL ReadAndPrintInt(STRING filename)()
  FILE fileHandle;
  INT value WIDTH 8;

  fileHandle := FOPEN(filename, "r");

  IF FERROR() THEN
    PRINT("ERROR: Cannot open file ", filename, "\n");
    EXIT;
  END;

  DO
    value := FGETI(fileHandle, WIDTHOF(value));
  WHILE !(FERROR(fileHandle) || FEOF(fileHandle))
    PRINT("0x", HEX(value), "\n");
  END;

  FCLOSE(fileHandle);
END;

The example will read and print out the contents of the file in hex a byte at a time.

Non 8 bit widths and endianness

The following example demonstrates how non-aligned reads work and how endianness affects reads with widths greater than 8:

// File contents: 12 34 56 78 9a bc de f0

INT x;

x := FGETI(file,  4);    // returns 0x02
x := FGETI(file,  4);    // returns 0x01
x := FGETI(file,  8);    // returns 0x34
x := FGETI(file, 16);    // returns 0x7856
x := FGETI(file, 32);    // returns 0xf0debc9a

N.B. If the data is required in big-endian format, it can be reversed simply using bit selections. E.g. for a 32 bit number:

x := x[7..0,15..8,23..16,31..24];

See Also