FGETS

The FGETS function reads a string from a file, until it reaches the end of a line or reaches the end of the file.

A string is a series of whole bytes. Reading a string causes the file handle to move forward to the next byte boundary before reading starts. Data is then read until either a newline (\n) character or the end of file is reached. Any newline (\n) and carriage return (\r) characters are returned as part of the string.

Syntax

FGETS( FILE fileHandle )

Parameters

fileHandle
The file handle to read from.

Return value

A STRING value containing the next line of text from the file.

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.

End of file

If the file being read has a carriage return at the end of the last line, then FEOF is not set until an attempt is made to read a line after the last one has been read and FGETS returns an empty string. If the file has no carriage return at the end of the last line then FGETS returns that last line without any trailing carriage return and FEOF is set immediately.

Example

LOCAL PrintFile(STRING filename)()
  FILE fileHandle;
  STRING line;
        
  fileHandle := FOPEN(filename, "r");
  IF FERROR() THEN
    PRINT("ERROR: Cannot open file ", filename, "\n");
    EXIT;
  END;

  DO
    line := FGETS(fileHandle);
    IF !FERROR(fileHandle) THEN
      PRINT(line);
    END;
  WHILE !(FEOF(fileHandle) || FERROR(fileHandle))
  END;
        
  FCLOSE(fileHandle);
END;

See Also