FOPEN

The FOPEN function is used to open a file so that it can be read from or written to.

If the filename is a relative path see How files are located for more information on how the filename is handled.

Files inside XJPack Files cannot be opened for writing or appending — FOPEN will fail and FERROR will return true. The parameterless version of FERROR must be used, because if FOPEN fails, the file handle will not have been initialised and so cannot be passed into FERROR.

Syntax

FOPEN( STRING filename, STRING fileMode )

Parameters

filename
The path to the file to open.
fileMode

Specifies the mode in which the file should be opened. It can be one of the following values:

Mode Read Write File exists File does not exist
r Yes No The file is opened and its contents are preserved. FOPEN fails and the FERROR flag is set.
w No Yes The contents of the file are destroyed. A new file is created.
a No Yes† The file is opened and its contents are preserved. A new file is created.
r+ Yes Yes The file is opened and its contents are preserved. FOPEN fails and the FERROR flag is set.
w+ Yes Yes The contents of the file are destroyed. A new file is created.
a+ Yes Yes† The file is opened and its contents are preserved. A new file is created.

† Any writes to a file opened in append mode will occur at the end of the file. Even if you use FSEEK to move to another location in the file, the current position will automatically move to the end before any subsequent write.

The 'b' and 't' options, formerly used to specify that the file should be opened in binary or text mode, have been deprecated and will be ignored. All files are now opened in binary mode.

Return value

A FILE handle that can be used to access the opened file.

Example

// Function to append the contents of one file to the end of the
// second file.
//
// Returns result = TRUE on success
//
LOCAL AppendFile(STRING filename1, STRING filename2)(INT result)
  FILE fileHandle1, fileHandle2;
  INT value WIDTH 32;

  result := FALSE;

  fileHandle1 := FOPEN(filename1, "r");
  IF FERROR() THEN
    PRINT("Error opening ", filename1, "\n");
    RETURN;
  END;

  fileHandle2 := FOPEN(filename2, "a");
  IF FERROR() THEN
    PRINT("Error opening ", filename2, "\n");
    RETURN;
  END;

  DO
    value := FGETI(fileHandle1, WIDTHOF(value));
  WHILE !(FEOF(fileHandle) ||? FERROR(fileHandle))
    FWRITE(fileHandle2, value);
    IF FERROR(fileHandle) THEN
      PRINT("Error writing to file ", filename2, "\n");
      FCLOSE(fileHandle1);
      FCLOSE(fileHandle2);
      RETURN;
    END;
  END;
  IF FERROR(fileHandle)
    PRINT("Error reading file ", filename1, "\n");
    FCLOSE(fileHandle1);
    FCLOSE(fileHandle2);
    RETURN;
  END;

  FCLOSE(fileHandle1);
  FCLOSE(fileHandle2);

  result := TRUE;
END;