Input and Output
****************

Octave supports several ways of reading and writing data to or from the prompt or a file.  The simplest functions for data Input and Output (I/O) are easy to use, but only provide limited control of how data is processed.  For more control, a set of functions modeled after the C standard library are also provided by Octave.

Basic Input and Output
======================

Terminal Output
---------------

Since Octave normally prints the value of an expression as soon as it has been evaluated, the simplest of all I/O functions is a simple expression.  For example, the following expression will display the value of pi

     pi
          -| ans =  3.1416

This works well as long as it is acceptable to have the name of the variable (or ans) printed along with the value.  To print the value of a variable without printing its name, use the function disp.

The format command offers some control over the way Octave prints values with disp and through the normal echoing mechanism.

 -- disp: (X)
 -- STR =: disp (X)
     Display the value of X.

     For example:

          disp ("The value of pi is:"), disp (pi)

               -| the value of pi is:
               -| 3.1416

     Note that the output from disp always ends with a newline.

     If an output value is requested, disp prints nothing and returns the formatted output in a string. fdisp

 -- STR =: list_in_columns (ARG, WIDTH, PREFIX)
     Return a string containing the elements of ARG listed in columns with an overall maximum width of WIDTH and optional prefix PREFIX.

     The argument ARG must be a cell array of character strings or a character array.

     If WIDTH is not specified or is an empty matrix, or less than or equal to zero, the width of the terminal screen is used.  Newline characters are used to break the lines in the output string.  For example:

          list_in_columns ({"abc", "def", "ghijkl", "mnop", "qrs", "tuv"}, 20)
               => abc     mnop
                  def     qrs
                  ghijkl  tuv

          whos ans
               =>
               Variables in the current scope:

                 Attr Name        Size                     Bytes  Class
                 ==== ====        ====                     =====  =====
                      ans         1x37                        37  char

               Total is 37 elements using 37 bytes

     terminal_size

 -- [ROWS, COLS] =: terminal_size ()
 -- terminal_size: ([ROWS, COLS])
     Query or set the size of the terminal window.  If called with no arguments, return a two-element row vector containing the current size of the terminal window in characters (rows and columns).  If called with a two-element vector of integer values, set the terminal size and return the previous setting. Setting the size manually should not be needed when using readline for command-line editing. list_in_columns

 -- format:
 -- format: options
 -- format: (OPTIONS)
 -- [FORMAT, FORMATSPACING, UPPERCASE] =: format
     Reset or specify the format of the output produced by disp and Octave's normal echoing mechanism.

     This command only affects the display of numbers, not how they are stored or computed.  To change the internal representation from the default double use one of the conversion functions such as single, uint8, int64, etc.  Any format options that change the number of displayed significant digits will also be reflected by the output_precision function.

     By default, Octave displays 5 significant digits in a human readable form (option short, option lowercase, and option loose format for matrices).  If format is invoked without any options, or the option default is specified, then this default format is restored.

     Valid format options for floating point numbers are listed in the following table.

     default
          Restore the default format state described above.

     short
          Fixed point format with 5 significant figures (default).

     long
          Fixed point format with 16 significant figures.

          As with the short format, Octave will switch to an exponential e format if it is unable to format a matrix properly using the current format.

     shorte
     longe
          Exponential format.  The number to be represented is split between a mantissa and an exponent (power of 10).  The mantissa has 5 significant digits in the short format.  In the long format, double values are displayed with 16 significant digits and single values are displayed with 8.  For example, with the shorte format, pi is displayed as 3.1416e+00. Optionally, the trailing e can be split into a second argument.

     shortg
     longg
          Optimally choose between fixed point and exponential format based on the magnitude of the number.  For example, with the shortg format, pi .^ [2; 4; 8; 16; 32] is displayed as

               ans =

                     9.8696
                     97.409
                     9488.5
                 9.0032e+07
                 8.1058e+15

          Optionally, the trailing g can be split into a second argument.

     shorteng
     longeng
          Identical to shorte or longe but displays the value using an engineering format, where the exponent is divisible by 3.  For example, with the shorteng format, 10 * pi is displayed as 31.416e+00. Optionally, the trailing eng can be split into a second argument.

     free
     none
          Print output in free format, without trying to line up columns of matrices on the decimal point.  This is a raw format equivalent to the C++ code std::cout << VARIABLE.  In general, the result is a presentation with 6 significant digits where unnecessary precision (such as trailing zeros for integers) is suppressed.  Complex numbers are formatted as numeric pairs like this (0.60419, 0.60709) instead of like this 0.60419 + 0.60709i.

     The following formats affect all numeric output (floating point and integer types).

     "+"
     "+" "CHARS"
     plus
     plus CHARS
          Print a + symbol for matrix elements greater than zero, a - symbol for elements less than zero, and a space for zero matrix elements.  This format can be useful for examining the sparsity structure of a large matrix. For very large matrices the function spy which plots the sparsity pattern will be clearer.

          The optional argument CHARS specifies a list of 3 characters to use for printing values greater than zero, less than zero, and equal to zero.  For example, with the format "+" "+-.", the matrix [1, 0, -1; -1, 0, 1] is displayed as

               ans =

               +.-
               -.+

     bank
          Print variable in a format appropriate for a currency (fixed format with two digits to the right of the decimal point).  Only the real part of a variable is displayed, as the imaginary part makes no sense for a currency.

     bit
          Print the bit representation of numbers in memory, always with the most significant bit first.  For example, pi is printed like this:

               0 10000000000 1001001000011111101101010100010001000010110100011000

          where spaces have been added for clarity to show the sign bit, the 11-bit exponent, and the 52-bit mantissa, in that order.  Together they represent pi as an IEEE 754 double precision floating point number in the normal form.  Single precision floating point numbers are analogous.

     native-bit
          Print the bit representation of numbers as stored in memory.  For big-endian machines, this is identical to the format bit layout seen above. For little-endian machines, it will print the bytes in the opposite order, though bits within a byte will still be presented with the most significant bit on the left.

          For example, the value of pi in this format on x86-64 is:

               00011000 00101101 01000100 01010100 11111011 00100001 00001001 01000000

          shown here with spaces added for clarity.  Compare with the previous bit string from format bit to see the grouping into bytes and their ordering.

     hex
          The same as format bit above, except that bits are grouped four at a time into hexadecimal digits for brevity.  Thus pi is represented as:

               400921fb54442d18

     native-hex
          The same as format native-bit above, except that bits are grouped four at a time into hexadecimal digits for brevity.  Thus pi is represented on an x86-64 as:

               182d4454fb210940

     rat
          Print a rational approximation, i.e., values are approximated as the ratio of small integers.  For example, with the rat format, pi is displayed as 355/113.

     The following two options affect the display of scientific and hex notations.

     lowercase (default)
          Use a lowercase e for the exponent character in scientific notation and lowercase a-f for the hex digits representing 10-15.

     uppercase
          Use an uppercase E for the exponent character in scientific notation and uppercase A-F for the hex digits representing 10-15.

     The following two options affect the display of all matrices.

     compact
          Remove blank lines around column number labels and between matrices producing more compact output with more data per page.

     loose (default)
          Insert blank lines above and below column number labels and between matrices to produce a more readable output with less data per page.

     If format is called with multiple competing options, the rightmost one is used, except for default which will override all other options.  In case of an error the format remains unchanged.

     If called with one to three output arguments, and no inputs, return the current format, format spacing, and uppercase preference.  Specifying both outputs and inputs will produce an error.

     fixed_point_format, output_precision, split_long_rows, print_empty_dimensions, rats

Paging Screen Output
....................

When running interactively, Octave normally sends all output directly to the Command Window.  However, when using the CLI version of Octave this can create a problem because large volumes of data will stream by before you can read them.  In such cases, it is better to use a paging program such as less or more which displays just one screenful at a time.  With less (and some versions of more) you can also scan forward and backward, and search for specific items.  The pager is enabled by the command more on.

Normally, no output is displayed by the pager until just before Octave is ready to print the top level prompt, or read from the standard input (for example, by using the fscanf or scanf functions).  This means that there may be some delay before any output appears on your screen if you have asked Octave to perform a significant amount of work with a single command statement.  The function fflush may be used to force output to be sent to the pager (or any other stream) immediately.

You can select the program to run as the pager with the PAGER function, and configure the pager itself with the PAGER_FLAGS function.

 -- more:
 -- more: on
 -- more: off
     Turn output pagination on or off.

     Without an argument, more toggles the current state.

     The current state can be determined via page_screen_output. page_screen_output, page_output_immediately, PAGER, PAGER_FLAGS

 -- VAL =: PAGER ()
 -- OLD_VAL =: PAGER (NEW_VAL)
 -- OLD_VAL =: PAGER (NEW_VAL, "local")
     Query or set the internal variable that specifies the program to use to display terminal output on your system.

     The default value is normally "less", "more", or "pg", depending on what programs are installed on your system. See Installation.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. PAGER_FLAGS, page_output_immediately, more, page_screen_output

 -- VAL =: PAGER_FLAGS ()
 -- OLD_VAL =: PAGER_FLAGS (NEW_VAL)
 -- OLD_VAL =: PAGER_FLAGS (NEW_VAL, "local")
     Query or set the internal variable that specifies the options to pass to the pager.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. PAGER, more, page_screen_output, page_output_immediately

 -- VAL =: page_screen_output ()
 -- OLD_VAL =: page_screen_output (NEW_VAL)
 -- OLD_VAL =: page_screen_output (NEW_VAL, "local")
     Query or set the internal variable that controls whether output intended for the terminal window that is longer than one page is sent through a pager.

     This allows you to view one screenful at a time.  Some pagers (such as less---see Installation) are also capable of moving backward on the output.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. more, page_output_immediately, PAGER, PAGER_FLAGS

 -- VAL =: page_output_immediately ()
 -- OLD_VAL =: page_output_immediately (NEW_VAL)
 -- OLD_VAL =: page_output_immediately (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave sends output to the pager as soon as it is available.

     When the value is false, Octave buffers its output and waits until just before the prompt is printed to flush it to the pager.  This is the default.

     When page_screen_output is false, this variable has no effect.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. page_screen_output, more, PAGER, PAGER_FLAGS

 -- STATUS =: fflush (FID)
     Flush output to file descriptor FID.

     fflush returns 0 on success and an OS dependent error value (-1 on Unix) on error.

     Programming Note: Flushing is useful for ensuring that all pending output makes it to the screen before some other event occurs.  For example, it is always a good idea to flush the standard output stream before calling input. fopen, fclose

Terminal Input
--------------

Octave has three functions that make it easy to prompt users for input.  The input and menu functions are normally used for managing an interactive dialog with a user, and the keyboard function is normally used for doing simple debugging.

 -- ANS =: input (PROMPT)
 -- ANS =: input (PROMPT, "s")
     Print PROMPT and wait for user input.

     For example,

          input ("Pick a number, any number! ")

     prints the prompt

          Pick a number, any number!

     and waits for the user to enter a value.  The string entered by the user is evaluated as an expression, so it may be a literal constant, a variable name, or any other valid Octave code.

     The number of return arguments, their size, and their class depend on the expression entered.

     If you are only interested in getting a literal string value, you can call input with the character string "s" as the second argument. This tells Octave to return the string entered by the user directly, without evaluating it first.

     Because there may be output waiting to be displayed by the pager, it is a good idea to always call fflush (stdout) before calling input. This will ensure that all pending output is written to the screen before your prompt. yes_or_no, kbhit, pause, menu, listdlg

 -- CHOICE =: menu (TITLE, OPT1, ...)
 -- CHOICE =: menu (TITLE, {OPT1, ...})
     Display a menu with heading TITLE and options OPT1, ..., and wait for user input.

     If the GUI is running, the menu is displayed graphically using listdlg.  Otherwise, the title and menu options are printed on the console.

     TITLE is a string and the options may be input as individual strings or as a cell array of strings.

     The return value CHOICE is the number of the option selected by the user counting from 1.  If the user aborts the dialog or makes an invalid selection then 0 is returned.

     This function is useful for interactive programs.  There is no limit to the number of options that may be passed in, but it may be confusing to present more than will fit easily on one screen. input, listdlg

 -- ANS =: yes_or_no ("PROMPT")
     Ask the user a yes-or-no question.

     Return logical true if the answer is yes or false if the answer is no.

     Takes one argument, PROMPT, which is the string to display when asking the question.  PROMPT should end in a space; yes-or-no adds the string (yes or no)  to it.  The user must confirm the answer with RET and can edit it until it has been confirmed. input

For input, the normal command line history and editing functions are available at the prompt.

Octave also has a function that makes it possible to get a single character from the keyboard without requiring the user to type a carriage return.

 -- C =: kbhit ()
 -- C =: kbhit (1)
     Read a single keystroke from the keyboard.

     If called with an argument (typically 1), don't wait for a keypress and immediately return the next keystroke in the keyboard input buffer or an empty string ("") if no keystroke is available.

     For example,

          c = kbhit ();

     will set C to the next character typed at the keyboard as soon as it is typed.

          c = kbhit (1);

     is identical to the above example, but doesn't wait for a keypress, returning the empty string if no key is available. input, pause

Simple File I/O
---------------

The save and load commands allow data to be written to and read from disk files in various formats.  The default format of files written by the save command can be controlled using the functions save_default_options and save_precision.

As an example the following code creates a 3-by-3 matrix and saves it to the file myfile.mat.

     A = [ 1:3; 4:6; 7:9 ];
     save myfile.mat A

Once one or more variables have been saved to a file, they can be read into memory using the load command.

     load myfile.mat
     A
          -| A =
          -|
          -|    1   2   3
          -|    4   5   6
          -|    7   8   9

 -- save: file
 -- save: options file
 -- save: options file V1 V2 ...
 -- save: options file -struct STRUCT
 -- save: options file -struct STRUCT F1 F2 ...
 -- save: - V1 V2 ...
 -- STR =: save ("-", "V1", "V2", ...)
     Save the named variables V1, V2, ..., in the file FILE.

     The special filename - may be used to return the content of the variables as a string.  If no variable names are listed, Octave saves all the variables in the current scope.  Otherwise, full variable names or pattern syntax can be used to specify the variables to save.  If the -struct modifier is used then the fields of the scalar struct are saved as if they were variables with the corresponding field names.  The -struct option can be combined with specific field names F1, F2, ... to write only certain fields to the file.

     Valid options for the save command are listed in the following table. Options that modify the output format override the format specified by save_default_options.

     If save is invoked using the functional form

          save ("-option1", ..., "file", "v1", ...)

     then the OPTIONS, FILE, and variable name arguments (V1, ...) must be specified as character strings.

     If called with a filename of "-", write the output to stdout if nargout is 0, otherwise return the output in a character string.

     -append
          Append to the destination instead of overwriting.

     -ascii
          Save a matrix in a text file without a header or any other information.  The matrix must be 2-D and only the real part of any complex value is written to the file.  Numbers are stored in single-precision format and separated by spaces.  Additional options for the -ascii format are

          -double
               Store numbers in double-precision format.

          -tabs
               Separate numbers with tabs.

     -binary
          Save the data in Octave's binary data format.

     -float-binary
          Save the data in Octave's binary data format but using only single precision. Use this format only if you know that all the values to be saved can be represented in single precision.

     -hdf5
          Save the data in HDF5 format.  (HDF5 is a free, portable, binary format developed by the National Center for Supercomputing Applications at the University of Illinois.) This format is only available if Octave was built with a link to the HDF5 libraries.

     -float-hdf5
          Save the data in HDF5 format but using only single precision.  Use this format only if you know that all the values to be saved can be represented in single precision.

     -text
          Save the data in Octave's text data format.  (default)

     -v7.3
     -V7.3
     -7.3
          Octave does not yet implement saving in MATLAB's v7.3 binary data format.

     -v7
     -V7
     -7
     -mat7-binary
          Save the data in MATLAB's v7 binary data format.

     -v6
     -V6
     -6
     -mat
     -mat-binary
          Save the data in MATLAB's v6 binary data format.

     -v4
     -V4
     -4
     -mat4-binary
          Save the data in MATLAB's v4 binary data format.

     -zip
     -z
          Use the gzip algorithm to compress the file.  This works on files that are compressed with gzip outside of Octave, and gzip can also be used to convert the files for backward compatibility.  This option is only available if Octave was built with a link to the zlib libraries.

     The list of variables to save may use wildcard patterns (glob patterns) containing the following special characters:

     ?
          Match any single character.

     *
          Match zero or more characters.

     [ LIST ]
          Match the list of characters specified by LIST.  If the first character is ! or ^, match all characters except those specified by LIST.  For example, the pattern [a-zA-Z] will match all lower and uppercase alphabetic characters.

          Wildcards may also be used in the field name specifications when using the -struct modifier (but not in the struct name itself).

     Except when using the MATLAB binary data file format or the -ascii format, saving global variables also saves the global status of the variable. If the variable is restored at a later time using load, it will be restored as a global variable.

     Example:

     The command

          save -binary data a b*

     saves the variable a and all variables beginning with b to the file data in Octave's binary format. load, save_default_options, save_header_format_string, save_precision, dlmread, csvread, fread

There are three functions that modify the behavior of save.

 -- VAL =: save_default_options ()
 -- OLD_VAL =: save_default_options (NEW_VAL)
 -- OLD_VAL =: save_default_options (NEW_VAL, "local")
     Query or set the internal variable that specifies the default options for the save command, and defines the default format.

     The default value is "-text" (Octave's own text-based file format). See the documentation of the save command for other choices.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. save, save_header_format_string, save_precision

 -- VAL =: save_precision ()
 -- OLD_VAL =: save_precision (NEW_VAL)
 -- OLD_VAL =: save_precision (NEW_VAL, "local")
     Query or set the internal variable that specifies the number of digits to keep when saving data in text format.

     The default value is 17 which is the minimum necessary for the lossless saving and restoring of IEEE-754 double values; For IEEE-754 single values the minimum value is 9.  If file size is a concern, it is probably better to choose a binary format for saving data rather than to reduce the precision of the saved values.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

     save_default_options

 -- VAL =: save_header_format_string ()
 -- OLD_VAL =: save_header_format_string (NEW_VAL)
 -- OLD_VAL =: save_header_format_string (NEW_VAL, "local")
     Query or set the internal variable that specifies the format string used for the comment line written at the beginning of text-format data files saved by Octave.

     The format string is passed to strftime and must begin with the character # and contain no newline characters.  If the value of save_header_format_string is the empty string, the header comment is omitted from text-format data files.  The default value is

          "# Created by Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. strftime, save_default_options

 -- load: file
 -- load: options file
 -- load: options file v1 v2 ...
 -- S =: load ("options", "file", "v1", "v2", ...)
 -- load: file options
 -- load: file options v1 v2 ...
 -- S =: load ("file", "options", "v1", "v2", ...)
     Load the named variables V1, V2, ..., from the file FILE.

     If no variables are specified then all variables found in the file will be loaded.  As with save, the list of variables to extract can be full names or use a pattern syntax.  The format of the file is automatically detected but may be overridden by supplying the appropriate option.

     If load is invoked using the functional form

          load ("-option1", ..., "file", "v1", ...)

     then the OPTIONS, FILE, and variable name arguments (V1, ...) must be specified as character strings.

     If a variable that is not marked as global is loaded from a file when a global symbol with the same name already exists, it is loaded in the global symbol table.  Also, if a variable is marked as global in a file and a local symbol exists, the local symbol is moved to the global symbol table and given the value from the file.

     If invoked with a single output argument, Octave returns data instead of inserting variables in the symbol table.  If the data file contains only numbers (TAB- or space-delimited columns), a matrix of values is returned.  Otherwise, load returns a structure with members corresponding to the names of the variables in the file.

     The load command can read data stored in Octave's text and binary formats, and MATLAB's binary format.  If compiled with zlib support, it can also load gzip-compressed files.  It will automatically detect the type of file and do conversion from different floating point formats (currently only IEEE big and little endian, though other formats may be added in the future).

     Valid options for load are listed in the following table.

     -force
          This option is accepted for backward compatibility but is ignored. Octave now overwrites variables currently in memory with those of the same name found in the file.

     -ascii
          Force Octave to assume the file contains columns of numbers in text format without any header or other information.  Data in the file will be loaded as a single numeric matrix with the name of the variable derived from the name of the file.

     -binary
          Force Octave to assume the file is in Octave's binary format.

     -hdf5
          Force Octave to assume the file is in HDF5 format.  (HDF5 is a free, portable binary format developed by the National Center for Supercomputing Applications at the University of Illinois.)  Note that load is only designed to read HDF5 files that were created by itself with save, and attempts to read other HDF5 files may fail or produce unpredictable results. The -hdf5 option also provides a limited ability to read files created using MATLAB's -v7.3 option (which saves in HDF5 format) although many data types are not yet supported. This format is only available if Octave was built with a link to the HDF5 libraries.

     -import
          This option is accepted for backward compatibility but is ignored. Octave can now support multi-dimensional HDF data and automatically modifies variable names if they are invalid Octave identifiers.

     -text
          Force Octave to assume the file is in Octave's text format.

     -v7.3
     -V7.3
     -7.3
          Octave does not yet implement MATLAB's v7.3 binary data format. As the v7.3 format is an HDF5 based format, the "-hdf5" option may be used to attempt to open a v7.3 format file, although most non-numeric data types are not yet supported.  Note that Octave can not currently save in this format.

     -v7
     -V7
     -7
     -mat7-binary
          Force Octave to assume the file is in MATLAB's version 7 binary format.

     -v6
     -V6
     -6
     -mat
     -mat-binary
          Force Octave to assume the file is in MATLAB's version 6 binary format.

     -v4
     -V4
     -4
     -mat4-binary
          Force Octave to assume the file is in MATLAB's version 4 binary format.

     save, dlmwrite, csvwrite, fwrite

 -- STR =: fileread (FILENAME)
 -- STR =: fileread (FILENAME, PARAM, VALUE, ...)
     Read the contents of FILENAME and return it as a string.

     PARAM, VALUE are optional pairs of parameters and values.  Valid options are:

     "Encoding"
          Specify encoding used when reading from the file.  This is a character string of a valid encoding identifier.  The default is "utf-8".

     fopen, fread, fscanf, importdata, textscan, type

 -- FMTSTR =: native_float_format ()
     Return the native floating point format as a string.

It is possible to write data to a file in a similar way to the disp function for writing data to the screen.  The fdisp works just like disp except its first argument is a file pointer as created by fopen.  As an example, the following code writes to data myfile.txt.

     fid = fopen ("myfile.txt", "w");
     fdisp (fid, "3/8 is ");
     fdisp (fid, 3/8);
     fclose (fid);

See Opening and Closing Files, for details on how to use fopen and fclose.

 -- fdisp: (FID, X)
     Display the value of X on the stream FID.

     For example:

          fdisp (stdout, "The value of pi is:"), fdisp (stdout, pi)

               -| the value of pi is:
               -| 3.1416

     Note that the output from fdisp always ends with a newline. disp

Octave can also read and write matrices text files such as comma separated lists.

 -- dlmwrite: (FILE, M)
 -- dlmwrite: (FILE, M, DELIM, R, C)
 -- dlmwrite: (FILE, M, KEY, VAL ...)
 -- dlmwrite: (FILE, M, "-append", ...)
 -- dlmwrite: (FID, ...)
     Write the numeric matrix M to the text file FILE using a delimiter.

     FILE should be a filename or a writable file ID given by fopen.

     The parameter DELIM specifies the delimiter to use to separate values on a row.  If no delimiter is specified the comma character , is used.

     The value of R specifies the number of delimiter-only lines to add to the start of the file.

     The value of C specifies the number of delimiters to prepend to each line of data.

     If the argument "-append" is given, append to the end of FILE.

     In addition, the following keyword value pairs may appear at the end of the argument list:

     "append"
          Either "on" or "off".  See "-append" above.

     "delimiter"
          See DELIM above.

     "newline"
          The character(s) to separate each row.  Three special cases exist for this option.  "unix" is changed into "\n", "pc" is changed into "\r\n", and "mac" is changed into "\r".  Any other value is used directly as the newline separator.

     "roffset"
          See R above.

     "coffset"
          See C above.

     "precision"
          The precision to use when writing the file.  It can either be a format string (as used by fprintf) or a number of significant digits.

          dlmwrite ("file.csv", reshape (1:16, 4, 4));

          dlmwrite ("file.tex", a, "delimiter", "&", "newline", "\n")

     dlmread, csvread, csvwrite

 -- DATA =: dlmread (FILE)
 -- DATA =: dlmread (FILE, SEP)
 -- DATA =: dlmread (FILE, SEP, R0, C0)
 -- DATA =: dlmread (FILE, SEP, RANGE)
 -- DATA =: dlmread (..., "emptyvalue", EMPTYVAL)
     Read numeric data from the text file FILE which uses the delimiter SEP between data values.

     If SEP is not defined the separator between fields is determined from the file itself.

     The optional scalar arguments R0 and C0 define the starting row and column of the data to be read.  These values are indexed from zero, i.e., the first data row corresponds to an index of zero.

     The RANGE parameter specifies exactly which data elements are read. The first form of the parameter is a 4-element vector containing the upper left and lower right corners [R0,C0,R1,C1] where the indices are zero-based.  To specify the last column---the equivalent of end when indexing---use the specifier Inf.  Alternatively, a spreadsheet style form such as "A2..Q15" or "T1:AA5" can be used.  The lowest alphabetical index 'A' refers to the first column. The lowest row index is 1.

     FILE should be a filename or a file id given by fopen.  In the latter case, the file is read until end of file is reached.

     The "emptyvalue" option may be used to specify the value used to fill empty fields.  The default is zero.  Note that any non-numeric values, such as text, are also replaced by the "emptyvalue". csvread, textscan, dlmwrite

 -- csvwrite: (FILENAME, X)
 -- csvwrite: (FILENAME, X, DLM_OPT1, ...)
     Write the numeric matrix X to the file FILENAME in comma-separated-value (CSV) format.

     This function is equivalent to

          dlmwrite (FILENAME, X, ",", DLM_OPT1, ...)

     Any optional arguments are passed directly to dlmwrite (see dlmwrite). csvread, dlmwrite, dlmread

 -- X =: csvread (FILENAME)
 -- X =: csvread (FILENAME, DLM_OPT1, ...)
     Read the comma-separated-value (CSV) file FILENAME into the matrix X.

     Note: only CSV files containing numeric data can be read.

     This function is equivalent to

          X = dlmread (FILENAME, "," , DLM_OPT1, ...)

     Any optional arguments are passed directly to dlmread (see dlmread). dlmread, textscan, csvwrite, dlmwrite

Formatted data from can be read from, or written to, text files as well.

 -- [A, ...] =: textread (FILENAME)
 -- [A, ...] =: textread (FILENAME, FORMAT)
 -- [A, ...] =: textread (FILENAME, FORMAT, N)
 -- [A, ...] =: textread (FILENAME, FORMAT, PROP1, VALUE1, ...)
 -- [A, ...] =: textread (FILENAME, FORMAT, N, PROP1, VALUE1, ...)

     This function is obsolete.  Use textscan instead.

     Read data from a text file.

     The file FILENAME is read and parsed according to FORMAT.  The function behaves like strread except it works by parsing a file instead of a string.  See the documentation of strread for details.

     In addition to the options supported by strread, this function supports two more:

       * "headerlines": The first VALUE number of lines of FILENAME are skipped.

       * "endofline": Specify a single character or "\r\n".  If no value is given, it will be inferred from the file.  If set to "" (empty string) EOLs are ignored as delimiters.

     The optional input N (format repeat count) specifies the number of times the format string is to be used or the number of lines to be read, whichever happens first while reading.  The former is equivalent to requesting that the data output vectors should be of length N. Note that when reading files with format strings referring to multiple lines, N should rather be the number of lines to be read than the number of format string uses.

     If the format string is empty (not just omitted) and the file contains only numeric data (excluding headerlines), textread will return a rectangular matrix with the number of columns matching the number of numeric fields on the first data line of the file.  Empty fields are returned as zero values.

     Examples:

            Assume a data file like:
            1 a 2 b
            3 c 4 d
            5 e

            [a, b] = textread (f, "%f %s")
            returns two columns of data, one with doubles, the other a
            cellstr array:
            a = [1; 2; 3; 4; 5]
            b = {"a"; "b"; "c"; "d"; "e"}

            [a, b] = textread (f, "%f %s", 3)
            (read data into two culumns, try to use the format string
            three times)
            returns
            a = [1; 2; 3]
            b = {"a"; "b"; "c"}

            With a data file like:
            1
            a
            2
            b

            [a, b] = textread (f, "%f %s", 2)
            returns a = 1 and b = {"a"}; i.e., the format string is used
            only once because the format string refers to 2 lines of the
            data file.  To obtain 2x1 data output columns, specify N = 4
            (number of data lines containing all requested data) rather
            than 2.

     textscan, load, dlmread, fscanf, strread

 -- C =: textscan (FID, FORMAT)
 -- C =: textscan (FID, FORMAT, REPEAT)
 -- C =: textscan (FID, FORMAT, PARAM, VALUE, ...)
 -- C =: textscan (FID, FORMAT, REPEAT, PARAM, VALUE, ...)
 -- C =: textscan (STR, ...)
 -- [C, POSITION, ERRMSG] =: textscan (...)
     Read data from a text file or string.

     The string STR or file associated with FID is read from and parsed according to FORMAT.  The function is an extension of strread and textread.  Differences include: the ability to read from either a file or a string, additional options, and additional format specifiers.

     The input is interpreted as a sequence of words, delimiters (such as whitespace), and literals.  The characters that form delimiters and whitespace are determined by the options.  The format consists of format specifiers interspersed between literals.  In the format, whitespace forms a delimiter between consecutive literals, but is otherwise ignored.

     The output C is a cell array where the number of columns is determined by the number of format specifiers.

     The first word of the input is matched to the first specifier of the format and placed in the first column of the output; the second is matched to the second specifier and placed in the second column and so forth.  If there are more words than specifiers then the process is repeated until all words have been processed or the limit imposed by REPEAT has been met (see below).

     The string FORMAT describes how the words in STR should be parsed.  As in FSCANF, any (non-whitespace) text in the format that is not one of these specifiers is considered a literal.  If there is a literal between two format specifiers then that same literal must appear in the input stream between the matching words.

     The following specifiers are valid:

     %f
     %f64
     %n
          The word is parsed as a number and converted to double.

     %f32
          The word is parsed as a number and converted to single (float).

     %d
     %d8
     %d16
     %d32
     %d64
          The word is parsed as a number and converted to int8, int16, int32, or int64.  If no size is specified then int32 is used.

     %u
     %u8
     %u16
     %u32
     %u64
          The word is parsed as a number and converted to uint8, uint16, uint32, or uint64.  If no size is specified then uint32 is used.

     %s
          The word is parsed as a string ending at the last character before whitespace, an end-of-line, or a delimiter specified in the options.

     %q
          The word is parsed as a "quoted string". If the first character of the string is a double quote (") then the string includes everything until a matching double quote---including whitespace, delimiters, and end-of-line characters.  If a pair of consecutive double quotes appears in the input, it is replaced in the output by a single double quote.  For examples, the input "He said ""Hello""" would return the value 'He said "Hello"'.

     %c
          The next character of the input is read. This includes delimiters, whitespace, and end-of-line characters.

     %[...]
     %[^...]
          In the first form, the word consists of the longest run consisting of only characters between the brackets.  Ranges of characters can be specified by a hyphen; for example, %[0-9a-zA-Z] matches all alphanumeric characters (if the underlying character set is ASCII).  Since MATLAB treats hyphens literally, this expansion only applies to alphanumeric characters.  To include '-' in the set, it should appear first or last in the brackets; to include ']', it should be the first character.  If the first character is '^' then the word consists of characters not listed.

     %N...
          For %s, %c %d, %f, %n, %u, an optional width can be specified as %Ns, etc. where N is an integer > 1.  For %c, this causes exactly N characters to be read instead of a single character.  For the other specifiers, it is an upper bound on the number of characters read; normal delimiters can cause fewer characters to be read.  For complex numbers, this limit applies to the real and imaginary components individually.  For %f and %n, format specifiers like %N.Mf are allowed, where M is an upper bound on number of characters after the decimal point to be considered; subsequent digits are skipped.  For example, the specifier %8.2f would read 12.345e6 as 1.234e7.

     %*...
          The word specified by the remainder of the conversion specifier is skipped.

     literals
          In addition the format may contain literal character strings; these will be skipped during reading.  If the input string does not match this literal, the processing terminates.

     Parsed words corresponding to the first specifier are returned in the first output argument and likewise for the rest of the specifiers.

     By default, if there is only one input argument, FORMAT is "%f". This means that numbers are read from the input into a single column vector. If FORMAT is explicitly empty ("") then textscan will return data in a number of columns matching the number of fields on the first data line of the input.  Either of these is suitable only when the input is exclusively numeric.

     For example, the string

          STR = "\
          Bunny Bugs   5.5\n\
          Duck Daffy  -7.5e-5\n\
          Penguin Tux   6"

     can be read using

          A = textscan (STR, "%s %s %f");

     The optional numeric argument REPEAT can be used for limiting the number of items read:

     -1
          Read all of the string or file until the end (default).

     N
          Read until the first of two conditions occurs: 1) the format has been processed N times, or 2) N lines of the input have been processed.  Zero (0) is an acceptable value for REPEAT.  Currently, end-of-line characters inside %q, %c, and %[...]$ conversions do not contribute to the line count.  This is incompatible with MATLAB and may change in future.

     The behavior of textscan can be changed via property/value pairs. The following properties are recognized:

     "BufSize"
          This specifies the number of bytes to use for the internal buffer. A modest speed improvement may be obtained by setting this to a large value when reading a large file, especially if the input contains long strings. The default is 4096, or a value dependent on N if that is specified.

     "CollectOutput"
          A value of 1 or true instructs textscan to concatenate consecutive columns of the same class in the output cell array.  A value of 0 or false (default) leaves output in distinct columns.

     "CommentStyle"
          Specify parts of the input which are considered comments and will be skipped.  VALUE is the comment style and can be either (1) A string or 1x1 cell string, to skip everything to the right of it; (2) A cell array of two strings, to skip everything between the first and second strings. Comments are only parsed where whitespace is accepted and do not act as delimiters.

     "Delimiter"
          If VALUE is a string, any character in VALUE will be used to split the input into words.  If VALUE is a cell array of strings, any string in the array will be used to split the input into words. (default value = any whitespace.)

     "EmptyValue"
          Value to return for empty numeric values in non-whitespace delimited data. The default is NaN.  When the data type does not support NaN (int32 for example), then the default is zero.

     "EndOfLine"
          VALUE can be either an empty or one character specifying the end-of-line character, or the pair "\r\n" (CRLF). In the latter case, any of "\r", "\n" or "\r\n" is counted as a (single) newline.  If no value is given, "\r\n" is used.

     "HeaderLines"
          The first VALUE number of lines of FID are skipped.  Note that this does not refer to the first non-comment lines, but the first lines of any type.

     "MultipleDelimsAsOne"
          If VALUE is nonzero, treat a series of consecutive delimiters, without whitespace in between, as a single delimiter.  Consecutive delimiter series need not be vertically aligned.  Without this option, a single delimiter before the end of the line does not cause the line to be considered to end with an empty value, but a single delimiter at the start of a line causes the line to be considered to start with an empty value.

     "TreatAsEmpty"
          Treat single occurrences (surrounded by delimiters or whitespace) of the string(s) in VALUE as missing values.

     "ReturnOnError"
          If set to numerical 1 or true, return normally as soon as an error is encountered, such as trying to read a string using %f. If set to 0 or false, return an error and no data.

     "Whitespace"
          Any character in VALUE will be interpreted as whitespace and trimmed; The default value for whitespace is " \b\r\n\t" (note the space).  Unless whitespace is set to "" (empty) AND at least one "%s" format conversion specifier is supplied, a space is always part of whitespace.

     When the number of words in STR or FID doesn't match an exact multiple of the number of format conversion specifiers, textscan's behavior depends on whether the last character of the string or file is an end-of-line as specified by the EndOfLine option:

     last character = end-of-line
          Data columns are padded with empty fields, NaN or 0 (for integer fields) so that all columns have equal length

     last character is not end-of-line
          Data columns are not padded; textscan returns columns of unequal length

     The second output POSITION provides the location, in characters from the beginning of the file or string, where processing stopped.

     dlmread, fscanf, load, strread, textread

The importdata function has the ability to work with a wide variety of data.

 -- A =: importdata (FNAME)
 -- A =: importdata (FNAME, DELIMITER)
 -- A =: importdata (FNAME, DELIMITER, HEADER_ROWS)
 -- [A, DELIMITER] =: importdata (...)
 -- [A, DELIMITER, HEADER_ROWS] =: importdata (...)
     Import data from the file FNAME.

     Input parameters:

       * FNAME The name of the file containing data.

       * DELIMITER The character separating columns of data.  Use \t for tab. (Only valid for ASCII files)

       * HEADER_ROWS The number of header rows before the data begins.  (Only valid for ASCII files)

     Different file types are supported:

       * ASCII table

          Import ASCII table using the specified number of header rows and the specified delimiter.

       * Image file

       * MATLAB file

       * Spreadsheet files (depending on external software)

       * WAV file

     textscan, dlmread, csvread, load

After importing, the data may need to be transformed before further analysis. The rescale function can shift and normalize a data set to a specified range.

 -- B =: rescale (A)
 -- B =: rescale (A, L, U)
 -- B =: rescale (..., "inputmin", INMIN)
 -- B =: rescale (..., "inputmax", INMAX)
     Scale matrix elements to a specified range of values.

     When called with a single matrix argument A, rescale elements to occupy the interval [0, 1].

     The optional inputs [L, U] will scale A to the interval with lower bound L and upper bound U.

     The optional input "inputmin" replaces all elements less than the specified value INMIN with INMIN.  Similarly, the optional input "inputmax" replaces all elements greater than the specified value INMAX with INMAX.  If unspecified the minimum and maximum are taken from the data itself (INMIN = min (A(:)) and INMAX = max (A(:))).

     Programming Notes: The applied formula is

     B = L + ((A - INMIN) ./ (INMAX - INMIN)) .* (U - L)

     The class of the output matrix B is single if the input A is single, but otherwise is of class double for inputs which are of double, integer, or logical type.

     bounds, min, max

Saving Data on Unexpected Exits
...............................

If Octave for some reason exits unexpectedly it will by default save the variables available in the workspace to a file in the current directory. By default this file is named octave-workspace and can be loaded into memory with the load command.  While the default behavior most often is reasonable it can be changed through the following functions.

 -- VAL =: crash_dumps_octave_core ()
 -- OLD_VAL =: crash_dumps_octave_core (NEW_VAL)
 -- OLD_VAL =: crash_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave tries to save all current variables to the file octave-workspace if it crashes or receives a hangup, terminate or similar signal.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. octave_core_file_limit, octave_core_file_name, octave_core_file_options

 -- VAL =: sighup_dumps_octave_core ()
 -- OLD_VAL =: sighup_dumps_octave_core (NEW_VAL)
 -- OLD_VAL =: sighup_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave tries to save all current variables to the file octave-workspace if it receives a hangup signal.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

 -- VAL =: sigquit_dumps_octave_core ()
 -- OLD_VAL =: sigquit_dumps_octave_core (NEW_VAL)
 -- OLD_VAL =: sigquit_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave tries to save all current variables to the file octave-workspace if it receives a quit signal.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

 -- VAL =: sigterm_dumps_octave_core ()
 -- OLD_VAL =: sigterm_dumps_octave_core (NEW_VAL)
 -- OLD_VAL =: sigterm_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave tries to save all current variables to the file octave-workspace if it receives a terminate signal.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

 -- VAL =: octave_core_file_options ()
 -- OLD_VAL =: octave_core_file_options (NEW_VAL)
 -- OLD_VAL =: octave_core_file_options (NEW_VAL, "local")
     Query or set the internal variable that specifies the options used for saving the workspace data if Octave aborts.

     The value of octave_core_file_options should follow the same format as the options for the save function.  The default value is Octave's binary format.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. crash_dumps_octave_core, octave_core_file_name, octave_core_file_limit

 -- VAL =: octave_core_file_limit ()
 -- OLD_VAL =: octave_core_file_limit (NEW_VAL)
 -- OLD_VAL =: octave_core_file_limit (NEW_VAL, "local")
     Query or set the internal variable that specifies the maximum amount of memory that Octave will save when writing a crash dump file.

     The limit is measured in kilobytes and is applied to the top-level workspace. The name of the crash dump file is specified by OCTAVE_CORE_FILE_NAME.

     If OCTAVE_CORE_FILE_OPTIONS flags specify a binary format, then OCTAVE_CORE_FILE_LIMIT will be approximately the maximum size of the file.  If a text file format is used, then the file could be much larger than the limit.  The default value is -1 (unlimited).

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. crash_dumps_octave_core, octave_core_file_name, octave_core_file_options

 -- VAL =: octave_core_file_name ()
 -- OLD_VAL =: octave_core_file_name (NEW_VAL)
 -- OLD_VAL =: octave_core_file_name (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the file used for saving data from the top-level workspace if Octave aborts.

     The default value is "octave-workspace"

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. crash_dumps_octave_core, octave_core_file_name, octave_core_file_options

C-Style I/O Functions
=====================

Octave's C-style input and output functions provide most of the functionality of the C programming language's standard I/O library.  The argument lists for some of the input functions are slightly different, however, because Octave has no way of passing arguments by reference.

In the following, FILE refers to a filename and fid refers to an integer file number, as returned by fopen.

There are three files that are always available.  Although these files can be accessed using their corresponding numeric file ids, you should always use the symbolic names given in the table below, since it will make your programs easier to understand.

 -- FID =: stdin ()
     Return the numeric value corresponding to the standard input stream.

     When Octave is used interactively, stdin is filtered through the command line editing functions. stdout, stderr

 -- FID =: stdout ()
     Return the numeric value corresponding to the standard output stream.

     Data written to the standard output may be filtered through the pager. stdin, stderr, page_screen_output

 -- FID =: stderr ()
     Return the numeric value corresponding to the standard error stream.

     Even if paging is turned on, the standard error is not sent to the pager. It is useful for error messages and prompts. stdin, stdout

Opening and Closing Files
-------------------------

When reading data from a file it must be opened for reading first, and likewise when writing to a file.  The fopen function returns a pointer to an open file that is ready to be read or written.  Once all data has been read from or written to the opened file it should be closed. The fclose function does this.  The following code illustrates the basic pattern for writing to a file, but a very similar pattern is used when reading a file.

     filename = "myfile.txt";
     fid = fopen (filename, "w");
     # Do the actual I/O here...
     fclose (fid);

 -- FID =: fopen (NAME)
 -- FID =: fopen (NAME, MODE)
 -- FID =: fopen (NAME, MODE, ARCH)
 -- FID =: fopen (NAME, MODE, ARCH, ENCODING)
 -- [FID, MSG] =: fopen (...)
 -- FID_LIST =: fopen ("all")
 -- [FILE, MODE, ARCH, ENCODING] =: fopen (FID)
     Open a file for low-level I/O or query open files and file descriptors.

     The first form of the fopen function opens the named file with the specified mode (read-write, read-only, etc.), architecture interpretation (IEEE big endian, IEEE little endian, etc.) and file encoding, and returns an integer value that may be used to refer to the file later.  If an error occurs, FID is set to -1 and MSG contains the corresponding system error message.  The MODE is a one or two character string that specifies whether the file is to be opened for reading, writing, or both.  The ENCODING is a character string with a valid encoding identifier.  This encoding is used when strings are read from or written to the file.  By default, that is UTF-8.

     The second form of the fopen function returns a vector of file ids corresponding to all the currently open files, excluding the stdin, stdout, and stderr streams.

     The third form of the fopen function returns information about the open file given its file id.

     For example,

          myfile = fopen ("splat.dat", "r", "ieee-le");

     opens the file splat.dat for reading.  If necessary, binary numeric values will be read assuming they are stored in IEEE format with the least significant bit first, and then converted to the native representation.

     Opening a file that is already open simply opens it again and returns a separate file id.  It is not an error to open a file several times, though writing to the same file through several different file ids may produce unexpected results.

     The possible values of MODE are

     r (default)
          Open a file for reading.

     w
          Open a file for writing.  The previous contents are discarded.

     a
          Open or create a file for writing at the end of the file.

     r+
          Open an existing file for reading and writing.

     w+
          Open a file for reading or writing.  The previous contents are discarded.

     a+
          Open or create a file for reading or writing at the end of the file.

     Append a "t" to the mode string to open the file in text mode or a "b" to open in binary mode.  On Windows systems, text mode reading and writing automatically converts linefeeds to the appropriate line end character for the system (carriage-return linefeed on Windows).  The default when no mode is specified is binary.

     Additionally, you may append a "z" to the mode string to open a gzipped file for reading or writing.  For this to be successful, you must also open the file in binary mode.

     The parameter ARCH is a string specifying the default data format for the file.  Valid values for ARCH are:

     "native" or "n" (default)
          The format of the current machine.

     "ieee-be" or "b"
          IEEE big endian format.

     "ieee-le" or "l"
          IEEE little endian format.

     When opening a new file that does not yet exist, permissions will be set to 0666 - UMASK.

     Compatibility Note: Octave opens files using buffered I/O.  Small writes are accumulated until an internal buffer is filled, and then everything is written in a single operation.  This is very efficient and improves performance. MATLAB, however, opens files using flushed I/O where every write operation is immediately performed.  If the write operation must be performed immediately after data has been written then the write should be followed by a call to fflush to flush the internal buffer. fclose, fgets, fgetl, fscanf, fread, fputs, fdisp, fprintf, fwrite, fskipl, fseek, frewind, ftell, feof, ferror, fclear, fflush, freport, umask

 -- STATUS =: fclose (FID)
 -- STATUS =: fclose ("all")
     Close the file specified by the file descriptor FID.

     If successful, fclose returns 0, otherwise, it returns -1.  The second form of the fclose call closes all open files except stdin, stdout, stderr, and any FIDs associated with gnuplot. fopen, fflush, freport

 -- TF =: is_valid_file_id (FID)
     Return true if FID refers to an open file. freport, fopen

Simple Output
-------------

Once a file has been opened for writing a string can be written to the file using the fputs function.  The following example shows how to write the string Free Software is needed for Free Science to the file free.txt.

     filename = "free.txt";
     fid = fopen (filename, "w");
     fputs (fid, "Free Software is needed for Free Science");
     fclose (fid);

 -- STATUS =: fputs (FID, STRING)
     Write the string STRING to the file with file descriptor FID.

     The string is written to the file with no additional formatting.  Use fdisp instead to automatically append a newline character appropriate for the local machine.

     The optional output STATUS is 0 for success, or -1 if an error was encountered. fdisp, fprintf, fwrite, fopen

A function much similar to fputs is available for writing data to the screen.  The puts function works just like fputs except it doesn't take a file pointer as its input.

 -- STATUS =: puts (STRING)
     Write a string to the standard output with no formatting.

     The string is written verbatim to the standard output.  Use disp to automatically append a newline character appropriate for the local machine.

     The optional output STATUS is 0 for success, or -1 if an error was encountered. fputs, disp

Line-Oriented Input
-------------------

To read from a file it must be opened for reading using fopen. Then a line can be read from the file using fgetl as the following code illustrates

     fid = fopen ("free.txt");
     txt = fgetl (fid)
          -| Free Software is needed for Free Science
     fclose (fid);

This of course assumes that the file free.txt exists and contains the line Free Software is needed for Free Science.

 -- STR =: fgetl (FID)
 -- STR =: fgetl (FID, LEN)
     Read characters from a file, stopping after a newline, or EOF, or LEN characters have been read.

     The characters read, excluding the possible trailing newline, are returned as a string.

     If LEN is omitted, fgetl reads until the next newline character.

     If there are no more characters to read, fgetl returns -1.

     To read a line and return the terminating newline, see fgets. fgets, fscanf, fread, fopen

 -- STR =: fgets (FID)
 -- STR =: fgets (FID, LEN)
     Read characters from a file, stopping after a newline, or EOF, or LEN characters have been read.

     The characters read, including the possible trailing newline, are returned as a string.

     If LEN is omitted, fgets reads until the next newline character.

     If there are no more characters to read, fgets returns -1.

     To read a line and discard the terminating newline, see fgetl. fputs, fgetl, fscanf, fread, fopen

 -- NLINES =: fskipl (FID)
 -- NLINES =: fskipl (FID, COUNT)
 -- NLINES =: fskipl (FID, Inf)
     Read and skip COUNT lines from the file specified by the file descriptor FID.

     fskipl discards characters until an end-of-line is encountered exactly COUNT-times, or until the end-of-file marker is found.

     If COUNT is omitted, it defaults to 1.  COUNT may also be Inf, in which case lines are skipped until the end of the file. This form is suitable for counting the number of lines in a file.

     Returns the number of lines skipped (end-of-line sequences encountered). fgetl, fgets, fscanf, fopen

Formatted Output
----------------

This section describes how to call printf and related functions.

The following functions are available for formatted output.  They are modeled after the C language functions of the same name, but they interpret the format template differently in order to improve the performance of printing vector and matrix values.

Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., "\n" => newline) are expanded even when the template string is defined with single quotes.

 -- printf: (TEMPLATE, ...)
 -- NUMBYTES =: printf (...)
     Print optional arguments under the control of the template string TEMPLATE to the stream stdout and return the number of characters printed.

     See the Formatted Output section of the GNU Octave manual for a complete description of the syntax of the template string.

     The optional output NUMBYTES returns the number of bytes printed.

     Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., "\n" => newline) are expanded even when the template string is defined with single quotes. fprintf, sprintf, scanf

 -- fprintf: (FID, TEMPLATE, ...)
 -- fprintf: (TEMPLATE, ...)
 -- NUMBYTES =: fprintf (...)
     This function is equivalent to printf, except that the output is written to the file descriptor FID instead of stdout.

     If FID is omitted, the output is written to stdout making the function exactly equivalent to printf.

     The optional output NUMBYTES returns the number of bytes written to the file.

     Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., "\n" => newline) are expanded even when the template string is defined with single quotes. fputs, fdisp, fwrite, fscanf, printf, sprintf, fopen

 -- STR =: sprintf (TEMPLATE, ...)
     This is like printf, except that the output is returned as a string.

     Unlike the C library function, which requires you to provide a suitably sized string as an argument, Octave's sprintf function returns the string, automatically sized to hold all of the items converted.

     Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., "\n" => newline) are expanded even when the template string is defined with single quotes. printf, fprintf, sscanf

The printf function can be used to print any number of arguments. The template string argument you supply in a call provides information not only about the number of additional arguments, but also about their types and what style should be used for printing them.

Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a % character in the template cause subsequent arguments to be formatted and written to the output stream.  For example,

     pct = 37;
     filename = "foo.txt";
     printf ("Processed %d%% of '%s'.\nPlease be patient.\n",
             pct, filename);

produces output like

     Processed 37% of 'foo.txt'.
     Please be patient.

This example shows the use of the %d conversion to specify that a scalar argument should be printed in decimal notation, the %s conversion to specify printing of a string argument, and the %% conversion to print a literal % character.

There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (%o, %u, or %x, respectively); or as a character value (%c).

Floating-point numbers can be printed in normal, fixed-point notation using the %f conversion or in exponential notation using the %e conversion.  The %g conversion uses either %e or %f format, depending on what is more appropriate for the magnitude of the particular number.

You can control formatting more precisely by writing modifiers between the % and the character that indicates which conversion to apply.  These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field.

The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion.  They're all described in more detail in the following sections.

Output Conversion for Matrices
------------------------------

When given a matrix value, Octave's formatted output functions cycle through the format template until all the values in the matrix have been printed.  For example:

     printf ("%4.2f %10.2e %8.4g\n", hilb (3));

          -| 1.00   5.00e-01   0.3333
          -| 0.50   3.33e-01     0.25
          -| 0.33   2.50e-01      0.2

If more than one value is to be printed in a single call, the output functions do not return to the beginning of the format template when moving on from one value to the next.  This can lead to confusing output if the number of elements in the matrices are not exact multiples of the number of conversions in the format template.  For example:

     printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]);

          -| 1.00   2.00e+00        3
          -| 4.00

If this is not what you want, use a series of calls instead of just one.

Output Conversion Syntax
------------------------

This section provides details about the precise syntax of conversion specifications that can appear in a printf template string.

Characters in the template string that are not part of a conversion specification are printed as-is to the output stream.

The conversion specifications in a printf template string have the general form:

     % FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION

For example, in the conversion specifier %-10.8ld, the - is a flag, 10 specifies the field width, the precision is 8, the letter l is a type modifier, and d specifies the conversion style.  (This particular type specifier says to print a numeric argument in decimal notation, with a minimum of 8 digits left-justified in a field at least 10 characters wide.)

In more detail, output conversion specifications consist of an initial % character followed in sequence by:

  * Zero or more flag characters that modify the normal behavior of the conversion specification.

  * An optional decimal integer specifying the minimum field width. If the normal conversion produces fewer characters than this, the field is padded with spaces to the specified width.  This is a minimum value; if the normal conversion produces more characters than this, the field is not truncated.  Normally, the output is right-justified within the field.

     You can also specify a field width of *.  This means that the next argument in the argument list (before the actual value to be printed) is used as the field width.  The value is rounded to the nearest integer.  If the value is negative, this means to set the - flag (see below) and to use the absolute value as the field width.

  * An optional precision to specify the number of digits to be written for the numeric conversions.  If the precision is specified, it consists of a period (.) followed optionally by a decimal integer (which defaults to zero if omitted).

     You can also specify a precision of *.  This means that the next argument in the argument list (before the actual value to be printed) is used as the precision.  The value must be an integer, and is ignored if it is negative.

  * An optional type modifier character.  This character is ignored by Octave's printf function, but is recognized to provide compatibility with the C language printf.

  * A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers.  See the descriptions of the individual conversions for information about the particular options that they use.

Table of Output Conversions
---------------------------

Here is a table summarizing what all the different conversions do:

%d, %i
     Print an integer as a signed decimal number.  See Integer Conversions, for details.  %d and %i are synonymous for output, but are different when used with scanf for input (see Table of Input Conversions).

%o
     Print an integer as an unsigned octal number.  See Integer Conversions, for details.

%u
     Print an integer as an unsigned decimal number.  See Integer Conversions, for details.

%x, %X
     Print an integer as an unsigned hexadecimal number.  %x uses lowercase letters and %X uses uppercase.  See Integer Conversions, for details.

%f
     Print a floating-point number in normal (fixed-point) notation. See Floating-Point Conversions, for details.

%e, %E
     Print a floating-point number in exponential notation.  %e uses lowercase letters and %E uses uppercase.  See Floating-Point Conversions, for details.

%g, %G
     Print a floating-point number in either normal (fixed-point) or exponential notation, whichever is more appropriate for its magnitude. %g uses lowercase letters and %G uses uppercase. See Floating-Point Conversions, for details.

%c
     Print a single character.  See Other Output Conversions.

%s
     Print a string.  See Other Output Conversions.

%%
     Print a literal % character.  See Other Output Conversions.

If the syntax of a conversion specification is invalid, unpredictable things will happen, so don't do this.  In particular, MATLAB allows a bare percentage sign % with no subsequent conversion character. Octave will emit an error and stop if it sees such code.  When the string variable to be processed cannot be guaranteed to be free of potential format codes it is better to use the two argument form of any of the printf functions and set the format string to %s.  Alternatively, for code which is not required to be backwards-compatible with MATLAB the Octave function puts or disp can be used.

     printf (strvar);        # Unsafe if strvar contains format codes
     printf ("%s", strvar);  # Safe
     puts (strvar);          # Safe

If there aren't enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable.  If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.

Integer Conversions
-------------------

This section describes the options for the %d, %i, %o, %u, %x, and %X conversion specifications.  These conversions print integers in various formats.

The %d and %i conversion specifications both print an numeric argument as a signed decimal number; while %o, %u, and %x print the argument as an unsigned octal, decimal, or hexadecimal number (respectively).  The %X conversion specification is just like %x except that it uses the characters ABCDEF as digits instead of abcdef.

The following flags are meaningful:

-
     Left-justify the result in the field (instead of the normal right-justification).

+
     For the signed %d and %i conversions, print a plus sign if the value is positive.

     For the signed %d and %i conversions, if the result doesn't start with a plus or minus sign, prefix it with a space character instead.  Since the + flag ensures that the result includes a sign, this flag is ignored if you supply both of them.

#
     For the %o conversion, this forces the leading digit to be 0, as if by increasing the precision.  For %x or %X, this prefixes a leading 0x or 0X (respectively) to the result.  This doesn't do anything useful for the %d, %i, or %u conversions.

0
     Pad the field with zeros instead of spaces.  The zeros are placed after any indication of sign or base.  This flag is ignored if the - flag is also specified, or if a precision is specified.

If a precision is supplied, it specifies the minimum number of digits to appear; leading zeros are produced if necessary.  If you don't specify a precision, the number is printed with as many digits as it needs.  If you convert a value of zero with an explicit precision of zero, then no characters at all are produced.

Floating-Point Conversions
--------------------------

This section discusses the conversion specifications for floating-point numbers: the %f, %e, %E, %g, and %G conversions.

The %f conversion prints its argument in fixed-point notation, producing output of the form [-]DDD.DDD, where the number of digits following the decimal point is controlled by the precision you specify.

The %e conversion prints its argument in exponential notation, producing output of the form [-]D.DDDe[+|-]DD. Again, the number of digits following the decimal point is controlled by the precision.  The exponent always contains at least two digits.  The %E conversion is similar but the exponent is marked with the letter E instead of e.

The %g and %G conversions print the argument in the style of %e or %E (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the %f style.  Trailing zeros are removed from the fractional portion of the result and a decimal-point character appears only if it is followed by a digit.

The following flags can be used to modify the behavior:

-
     Left-justify the result in the field.  Normally the result is right-justified.

+
     Always include a plus or minus sign in the result.

     If the result doesn't start with a plus or minus sign, prefix it with a space instead.  Since the + flag ensures that the result includes a sign, this flag is ignored if you supply both of them.

#
     Specifies that the result should always include a decimal point, even if no digits follow it.  For the %g and %G conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed.

0
     Pad the field with zeros instead of spaces; the zeros are placed after any sign.  This flag is ignored if the - flag is also specified.

The precision specifies how many digits follow the decimal-point character for the %f, %e, and %E conversions.  For these conversions, the default precision is 6.  If the precision is explicitly 0, this suppresses the decimal point character entirely.  For the %g and %G conversions, the precision specifies how many significant digits to print.  Significant digits are the first digit before the decimal point, and all the digits after it. If the precision is 0 or not specified for %g or %G, it is treated like a value of 1.  If the value being printed cannot be expressed precisely in the specified number of digits, the value is rounded to the nearest number that fits.

Other Output Conversions
------------------------

This section describes miscellaneous conversions for printf.

The %c conversion prints a single character.  The - flag can be used to specify left-justification in the field, but no other flags are defined, and no precision or type modifier can be given. For example:

     printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");

prints hello.

The %s conversion prints a string.  The corresponding argument must be a string.  A precision can be specified to indicate the maximum number of characters to write; otherwise characters in the string up to but not including the terminating null character are written to the output stream.  The - flag can be used to specify left-justification in the field, but no other flags or type modifiers are defined for this conversion.  For example:

     printf ("%3s%-6s", "no", "where");

prints  nowhere  (note the leading and trailing spaces).

Formatted Input
---------------

Octave provides the scanf, fscanf, and sscanf functions to read formatted input.  There are two forms of each of these functions.  One can be used to extract vectors of data from a file, and the other is more `C-like'.

 -- [VAL, COUNT, ERRMSG] =: fscanf (FID, TEMPLATE, SIZE)
 -- [V1, V2, ..., COUNT, ERRMSG] =: fscanf (FID, TEMPLATE, "C")
     In the first form, read from FID according to TEMPLATE, returning the result in the matrix VAL.

     The optional argument SIZE specifies the amount of data to read and may be one of

     Inf
          Read as much as possible, returning a column vector.

     NR
          Read up to NR elements, returning a column vector.

     [NR, Inf]
          Read as much as possible, returning a matrix with NR rows.  If the number of elements read is not an exact multiple of NR, the last column is padded with zeros.

     [NR, NC]
          Read up to NR * NC elements, returning a matrix with NR rows.  If the number of elements read is not an exact multiple of NR, the last column is padded with zeros.

     If SIZE is omitted, a value of Inf is assumed.

     A string is returned if TEMPLATE specifies only character conversions.

     The number of items successfully read is returned in COUNT.

     If an error occurs, ERRMSG contains a system-dependent error message.

     In the second form, read from FID according to TEMPLATE, with each conversion specifier in TEMPLATE corresponding to a single scalar return value.  This form is more ``C-like'', and also compatible with previous versions of Octave.  The number of successful conversions is returned in COUNT

     See the Formatted Input section of the GNU Octave manual for a complete description of the syntax of the template string. fgets, fgetl, fread, scanf, sscanf, fopen

 -- [VAL, COUNT, ERRMSG] =: scanf (TEMPLATE, SIZE)
 -- [V1, V2, ..., COUNT, ERRMSG] =: scanf (TEMPLATE, "C")
     This is equivalent to calling fscanf with FID = stdin.

     It is currently not useful to call scanf in interactive programs. fscanf, sscanf, printf

 -- [VAL, COUNT, ERRMSG, POS] =: sscanf (STRING, TEMPLATE, SIZE)
 -- [V1, V2, ..., COUNT, ERRMSG] =: sscanf (STRING, TEMPLATE, "C")
     This is like fscanf, except that the characters are taken from the string STRING instead of from a stream.

     Reaching the end of the string is treated as an end-of-file condition.  In addition to the values returned by fscanf, the index of the next character to be read is returned in POS. fscanf, scanf, sprintf

Calls to scanf are superficially similar to calls to printf in that arbitrary arguments are read under the control of a template string.  While the syntax of the conversion specifications in the template is very similar to that for printf, the interpretation of the template is oriented more towards free-format input and simple pattern matching, rather than fixed-field formatting. For example, most scanf conversions skip over any amount of ``white space'' (including spaces, tabs, and newlines) in the input file, and there is no concept of precision for the numeric input conversions as there is for the corresponding output conversions. Ordinarily, non-whitespace characters in the template are expected to match characters in the input stream exactly.  For example, note that sscanf parses the string and whitespace differently when using mixed numeric and string output types:

     teststr = "1 is a lonely number";
     sscanf (teststr, "%s is a %s")
     => 1lonelynumber

     sscanf (teststr, "%g is a %s")
     =>
          1
        108
        111
        110
        101
        108
        121

     [a, b, c] = sscanf ("1 is a lonely number", "%g is a %s %s", "C")
     => a =  1
     => b = lonely
     => c = number

When a matching failure occurs, scanf returns immediately, leaving the first non-matching character as the next character to be read from the stream, and scanf returns all the items that were successfully converted.

The formatted input functions are not used as frequently as the formatted output functions.  Partly, this is because it takes some care to use them properly.  Another reason is that it is difficult to recover from a matching error.

The specific flags and modifiers that are permitted in the template string and their interpretation are all described in more detail in the following sections.

Input Conversion Syntax
-----------------------

A scanf template string is a string that contains ordinary multibyte characters interspersed with conversion specifications that start with %.

Any whitespace character in the template causes any number of whitespace characters in the input stream to be read and discarded.  The whitespace characters that are matched need not be exactly the same whitespace characters that appear in the template string.  For example, write ,  in the template to recognize a comma with optional whitespace before and after.

Other characters in the template string that are not part of conversion specifications must match characters in the input stream exactly; if this is not the case, a matching failure occurs.

The conversion specifications in a scanf template string have the general form:

     % FLAGS WIDTH TYPE CONVERSION

In more detail, an input conversion specification consists of an initial % character followed in sequence by:

  * An optional flag character *, which says to ignore the text read for this specification.  When scanf finds a conversion specification that uses this flag, it reads input as directed by the rest of the conversion specification, but it discards this input, does not return any value, and does not increment the count of successful assignments.

  * An optional decimal integer that specifies the maximum field width.  Reading of characters from the input stream stops either when this maximum is reached or when a non-matching character is found, whichever happens first.  Most conversions discard initial whitespace characters, and these discarded characters don't count towards the maximum field width.  Conversions that do not discard initial whitespace are explicitly documented.

  * An optional type modifier character.  This character is ignored by Octave's scanf function, but is recognized to provide compatibility with the C language scanf.

  * A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers.  See the descriptions of the individual conversions in Table of Input Conversions for information about the particular options that they allow.

Table of Input Conversions
--------------------------

Here is a table that summarizes the various conversion specifications:

%d
     Matches an optionally signed integer written in decimal.  See Numeric Input Conversions.

%i
     Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant.  See Numeric Input Conversions.

%o
     Matches an unsigned integer written in octal radix. See Numeric Input Conversions.

%u
     Matches an unsigned integer written in decimal radix. See Numeric Input Conversions.

%x, %X
     Matches an unsigned integer written in hexadecimal radix. See Numeric Input Conversions.

%e, %f, %g, %E, %G
     Matches an optionally signed floating-point number.  See Numeric Input Conversions.

%s
     Matches a string containing only non-whitespace characters. See String Input Conversions.

%c
     Matches a string of one or more characters; the number of characters read is controlled by the maximum field width given for the conversion. See String Input Conversions.

%%
     This matches a literal % character in the input stream.  No corresponding argument is used.

If the syntax of a conversion specification is invalid, the behavior is undefined.  If there aren't enough function arguments provided to supply addresses for all the conversion specifications in the template strings that perform assignments, or if the arguments are not of the correct types, the behavior is also undefined.  On the other hand, extra arguments are simply ignored.

Numeric Input Conversions
-------------------------

This section describes the scanf conversions for reading numeric values.

The %d conversion matches an optionally signed integer in decimal radix.

The %i conversion matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant.

For example, any of the strings 10, 0xa, or 012 could be read in as integers under the %i conversion.  Each of these specifies a number with decimal value 10.

The %o, %u, and %x conversions match unsigned integers in octal, decimal, and hexadecimal radices, respectively.

The %X conversion is identical to the %x conversion.  They both permit either uppercase or lowercase letters to be used as digits.

By default, integers are read as 32-bit quantities.  With the h modifier, 16-bit integers are used, and with the l modifier, 64-bit integers are used.

The %e, %f, %g, %E, and %G conversions match optionally signed floating-point numbers.  All five conversion specifications behave identically, and will read in numerical values of any floating point display style.

String Input Conversions
------------------------

This section describes the scanf input conversions for reading string and character values: %s and %c.

The %c conversion is the simplest: it matches a fixed number of characters, always.  The maximum field with says how many characters to read; if you don't specify the maximum, the default is 1.  This conversion does not skip over initial whitespace characters.  It reads precisely the next N characters, and fails if it cannot get that many.

The %s conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something.

For example, reading the input:

      hello, world

with the conversion %10c produces " hello, wo", but reading the same input with the conversion %10s produces "hello,".

Binary I/O
----------

Octave can read and write binary data using the functions fread and fwrite, which are patterned after the standard C functions with the same names.  They are able to automatically swap the byte order of integer data and convert among the supported floating point formats as the data are read.

 -- VAL =: fread (FID)
 -- VAL =: fread (FID, SIZE)
 -- VAL =: fread (FID, SIZE, PRECISION)
 -- VAL =: fread (FID, SIZE, PRECISION, SKIP)
 -- VAL =: fread (FID, SIZE, PRECISION, SKIP, ARCH)
 -- [VAL, COUNT] =: fread (...)
     Read binary data from the file specified by the file descriptor FID.

     The optional argument SIZE specifies the amount of data to read and may be one of

     Inf
          Read as much as possible, returning a column vector.

     NR
          Read up to NR elements, returning a column vector.

     [NR, Inf]
          Read as much as possible, returning a matrix with NR rows.  If the number of elements read is not an exact multiple of NR, the last column is padded with zeros.

     [NR, NC]
          Read up to NR * NC elements, returning a matrix with NR rows.  If the number of elements read is not an exact multiple of NR, the last column is padded with zeros.

     If SIZE is omitted, a value of Inf is assumed.

     The optional argument PRECISION is a string specifying the type of data to read and may be one of

     "uint8" (default)
          8-bit unsigned integer.

     "int8"
     "integer*1"
          8-bit signed integer.

     "uint16"
     "ushort"
     "unsigned short"
          16-bit unsigned integer.

     "int16"
     "integer*2"
     "short"
          16-bit signed integer.

     "uint"
     "uint32"
     "unsigned int"
     "ulong"
     "unsigned long"
          32-bit unsigned integer.

     "int"
     "int32"
     "integer*4"
     "long"
          32-bit signed integer.

     "uint64"
          64-bit unsigned integer.

     "int64"
     "integer*8"
          64-bit signed integer.

     "single"
     "float"
     "float32"
     "real*4"
          32-bit floating point number.

     "double"
     "float64"
     "real*8"
          64-bit floating point number.

     "char"
     "char*1"
          8-bit single character.

     "uchar"
     "unsigned char"
          8-bit unsigned character.

     "schar"
     "signed char"
          8-bit signed character.

     The default precision is "uint8".

     The PRECISION argument may also specify an optional repeat count.  For example, 32*single causes fread to read a block of 32 single precision floating point numbers.  Reading in blocks is useful in combination with the SKIP argument.

     The PRECISION argument may also specify a type conversion. For example, int16=>int32 causes fread to read 16-bit integer values and return an array of 32-bit integer values.  By default, fread returns a double precision array.  The special form *TYPE is shorthand for TYPE=>TYPE.

     The conversion and repeat counts may be combined.  For example, the specification 32*single=>single causes fread to read blocks of single precision floating point values and return an array of single precision values instead of the default array of double precision values.

     The optional argument SKIP specifies the number of bytes to skip after each element (or block of elements) is read.  If it is not specified, a value of 0 is assumed.  If the final block read is not complete, the final skip is omitted.  For example,

          fread (f, 10, "3*single=>single", 8)

     will omit the final 8-byte skip because the last read will not be a complete block of 3 values.

     The optional argument ARCH is a string specifying the data format for the file.  Valid values are

     "native" or "n"
          The format of the current machine.

     "ieee-be" or "b"
          IEEE big endian.

     "ieee-le" or "l"
          IEEE little endian.

     If no ARCH is given the value used in the call to fopen which created the file descriptor is used.  Otherwise, the value specified with fread overrides that of fopen and determines the data format.

     The output argument VAL contains the data read from the file.

     The optional return value COUNT contains the number of elements read. fwrite, fgets, fgetl, fscanf, fopen

 -- COUNT =: fwrite (FID, DATA)
 -- COUNT =: fwrite (FID, DATA, PRECISION)
 -- COUNT =: fwrite (FID, DATA, PRECISION, SKIP)
 -- COUNT =: fwrite (FID, DATA, PRECISION, SKIP, ARCH)
     Write data in binary form to the file specified by the file descriptor FID.

     The argument DATA is a matrix of values that are to be written to the file.  The values are extracted in column-major order.

     The remaining arguments PRECISION, SKIP, and ARCH are optional, and are interpreted as described for fread.

     The output COUNT is the number of data items successfully written.

     Programming Note: The behavior of fwrite is undefined if the values in DATA are too large to fit in the specified precision. fread, fputs, fprintf, fopen

Temporary Files
---------------

Sometimes one needs to write data to a file that is only temporary. This is most commonly used when an external program launched from within Octave needs to access data.  When Octave exits all temporary files will be deleted, so this step need not be executed manually.

 -- [FID, NAME, MSG] =: mkstemp ("TEMPLATE")
 -- [FID, NAME, MSG] =: mkstemp ("TEMPLATE", DELETE)
     Return the file descriptor FID corresponding to a new temporary file with a unique name created from TEMPLATE.

     The last six characters of TEMPLATE must be "XXXXXX" and these are replaced with a string that makes the filename unique.  The file is then created with mode read/write and permissions that are system dependent (on GNU/Linux systems, the permissions will be 0600 for versions of glibc 2.0.7 and later).  The file is opened in binary mode and with the O_EXCL flag.

     If the optional argument DELETE is supplied and is true, the file will be deleted automatically when Octave exits.

     If successful, FID is a valid file ID, NAME is the name of the file, and MSG is an empty string.  Otherwise, FID is -1, NAME is empty, and MSG contains a system-dependent error message. tempname, tempdir, P_tmpdir, tmpfile, fopen

 -- [FID, MSG] =: tmpfile ()
     Return the file ID corresponding to a new temporary file with a unique name.

     The file is opened in binary read/write ("w+b") mode and will be deleted automatically when it is closed or when Octave exits.

     If successful, FID is a valid file ID and MSG is an empty string.  Otherwise, FID is -1 and MSG contains a system-dependent error message. tempname, mkstemp, tempdir, P_tmpdir

 -- FNAME =: tempname ()
 -- FNAME =: tempname (DIR)
 -- FNAME =: tempname (DIR, PREFIX)
     Return a unique temporary filename as a string.

     If PREFIX is omitted, a value of "oct-" is used.

     If DIR is also omitted, the default directory for temporary files (P_tmpdir) is used.  If DIR is provided, it must exist, otherwise the default directory for temporary files is used.

     Programming Note: Because the named file is not opened by tempname, it is possible, though relatively unlikely, that it will not be available by the time your program attempts to open it.  If this is a concern, see tmpfile. mkstemp, tempdir, P_tmpdir, tmpfile

 -- DIR =: tempdir ()
     Return the name of the host system's directory for temporary files.

     The directory name is taken first from the environment variable TMPDIR. If that does not exist, the environment variable TMP (and on Windows platforms also with higher priority the environment variable TEMP) is checked.  If none of those are set, the system default returned by P_tmpdir is used. P_tmpdir, tempname, mkstemp, tmpfile

 -- SYS_TMPDIR =: P_tmpdir ()
     Return the name of the host system's default directory for temporary files.

     Programming Note: The value returned by P_tmpdir is always the default location.  This value may not agree with that returned from tempdir if the user has overridden the default with the TMPDIR environment variable. tempdir, tempname, mkstemp, tmpfile

End of File and Errors
----------------------

Once a file has been opened its status can be acquired.  As an example the feof functions determines if the end of the file has been reached.  This can be very useful when reading small parts of a file at a time.  The following example shows how to read one line at a time from a file until the end has been reached.

     filename = "myfile.txt";
     fid = fopen (filename, "r");
     while (! feof (fid) )
       text_line = fgetl (fid);
     endwhile
     fclose (fid);

Note that in some situations it is more efficient to read the entire contents of a file and then process it, than it is to read it line by line.  This has the potential advantage of removing the loop in the above code.

 -- STATUS =: feof (FID)
     Return 1 if an end-of-file condition has been encountered for the file specified by file descriptor FID and 0 otherwise.

     Note that feof will only return 1 if the end of the file has already been encountered, not if the next read operation will result in an end-of-file condition. fread, frewind, fseek, fclear, fopen

 -- MSG =: ferror (FID)
 -- [MSG, ERR] =: ferror (FID)
 -- [...] =: ferror (FID, "clear")
     Query the error status of the stream specified by file descriptor FID.

     If an error condition exists then return a string MSG describing the error.  Otherwise, return an empty string "".

     The second input "clear" is optional.  If supplied, the error state on the stream will be cleared.

     The optional second output is a numeric indication of the error status. ERR is 1 if an error condition has been encountered and 0 otherwise.

     Note that ferror indicates if an error has already occurred, not whether the next operation will result in an error condition. fclear, fopen

 -- fclear: (FID)
     Clear the stream state for the file specified by the file descriptor FID. ferror, fopen

 -- freport: ()
     Print a list of which files have been opened, and whether they are open for reading, writing, or both.

     For example:

          freport ()

               -|  number  mode  arch       name
               -|  ------  ----  ----       ----
               -|     0     r    ieee-le    stdin
               -|     1     w    ieee-le    stdout
               -|     2     w    ieee-le    stderr
               -|     3     r    ieee-le    myfile

     fopen, fclose, is_valid_file_id

File Positioning
----------------

Three functions are available for setting and determining the position of the file pointer for a given file.

 -- POS =: ftell (FID)
     Return the position of the file pointer as the number of characters from the beginning of the file specified by file descriptor FID. fseek, frewind, feof, fopen

 -- STATUS =: fseek (FID, OFFSET)
 -- STATUS =: fseek (FID, OFFSET, ORIGIN)
     Set the file pointer to the location OFFSET within the file FID.

     The pointer is positioned OFFSET characters from the ORIGIN, which may be one of the predefined variables SEEK_SET (beginning), SEEK_CUR (current position), or SEEK_END (end of file) or strings "bof", "cof", or "eof".  If ORIGIN is omitted, SEEK_SET is assumed.  OFFSET may be positive, negative, or zero but not all combinations of ORIGIN and OFFSET can be realized.

     fseek returns 0 on success and -1 on error. fskipl, frewind, ftell, fopen, SEEK_SET, SEEK_CUR, SEEK_END

 -- FSEEK_ORIGIN =: SEEK_SET ()
     Return the numerical value to pass to fseek to position the file pointer relative to the beginning of the file. SEEK_CUR, SEEK_END, fseek

 -- FSEEK_ORIGIN =: SEEK_CUR ()
     Return the numerical value to pass to fseek to position the file pointer relative to the current position. SEEK_SET, SEEK_END, fseek

 -- FSEEK_ORIGIN =: SEEK_END ()
     Return the numerical value to pass to fseek to position the file pointer relative to the end of the file. SEEK_SET, SEEK_CUR, fseek

 -- frewind: (FID)
 -- STATUS =: frewind (FID)
     Move the file pointer to the beginning of the file specified by file descriptor FID.

     If an output STATUS is requested then frewind returns 0 for success, and -1 if an error is encountered.

     Programming Note: frewind is equivalent to fseek (FID, 0, SEEK_SET). fseek, ftell, fopen

The following example stores the current file position in the variable marker, moves the pointer to the beginning of the file, reads four characters, and then returns to the original position.

     marker = ftell (myfile);
     frewind (myfile);
     fourch = fgets (myfile, 4);
     fseek (myfile, marker, SEEK_SET);