fopen

Syntax

int fopen(string filename, string mode)

Arguments

filename
The full pathname of the file to open. Use double backslashes on Windows machines.
mode
The mode to open the file in, see below for details.

Return

Returns a pointer to the file stream that can be used in later file operations, if the file was opened successfully. Returns NULL if the file could not be opened.

Description

Opens a file or a stream, allowing it to be read from or written to. The mode can be any of a number of settings, including:
r Opens the file for reading.
w Opens the file for writing, overwriting any currently existing file.
a Opens the file in append mode, adding data to end of file or creating new file if doesn't exist.
rb Open a file in binary mode for reading only.
wb Open or create a file in binary mode for writing only.
r+ Opens the file for reading and writing.
w+ Opens the file for reading and writing, overwriting any currently existing file.
You can also specify whether the file should be opened in text or binary mode by adding 't' or 'b' to the mode string respectively. Text mode causes the program to interpret newlines differently depending on the machine it is operating on (Unix, Windows and Mac all have different newline endings). Binary mode is recommended for most operations on data files.

Example

int IMG_FILE;
if (IMG_FILE=fopen("d:\\FM_image0.fmi", "wb"))
{
  // Write out the src pixels as raw data
  for (z=0; z<Z; z++)
  for (y=0; y<Y; y++)
  for (x=0; x<X; x++)
    fputc(src(x,y,z), IMG_FILE);
}
else
  ErrorOk("Cannot write image file\nDrive is either full or write-protected!");

if (fclose(IMG_FILE))
  ErrorOk("Cannot close image file!");

Also see

fread, fwrite, fclose

Comments