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

There are two distinct classes of input and output functions.  The first set are modeled after the functions available in MATLAB.  The second set are modeled after the standard I/O library used by the C programming language and offer more flexibility and control over the output.

When running interactively, Octave normally sends any output intended for your terminal that is more than one screen long to a paging program, such as less or more.  This avoids the problem of having a large volume of output stream by before you can read it.  With less (and some versions of more) you can also scan forward and backward, and search for specific items.

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 by setting the variable PAGER, and you can turn paging off by setting the value of the variable page_screen_output to 0.

 -- Command: more
 -- Command: more on
 -- Command: more off
     Turn output pagination on or off.  Without an argument, more toggles the current state.

 -- Built-in Variable: PAGER
     The default value is normally "less", "more", or "pg", depending on what programs are installed on your system. See Installation.

     When running interactively, Octave sends any output intended for your terminal that is more than one screen long to the program named by the value of the variable PAGER.

 -- Built-in Variable: page_screen_output
     If the value of page_screen_output is nonzero, all output intended for the screen 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.  The default value is 1.

 -- Built-in Variable: page_output_immediately
     If the value of page_output_immediately is nonzero, Octave sends output to the pager as soon as it is available.  Otherwise, Octave buffers its output and waits until just before the prompt is printed to flush it to the pager.  The default value is 0.

 -- Built-in Function: fflush (FID)
     Flush output to FID.  This 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.

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

fopen, fclose

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
          -| pi = 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.

 -- Built-in Variable: ans
     This variable holds the most recently computed result that was not explicitly assigned to a variable.  For example, after the expression

          3^2 + 4^2

     is evaluated, the value of ans is 25.

 -- Built-in Function: 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

 -- Built-in Function: 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

 -- Command: format options
     Control the format of the output produced by disp and Octave's normal echoing mechanism.  Valid options are listed in the following table.

     short
          Octave will try to print numbers with at least 5 significant figures within a field that is a maximum of 10 characters wide (not counting additional spacing that is added between columns of a matrix).

          If Octave is unable to format a matrix so that columns line up on the decimal point and all the numbers fit within the maximum field width, it switches to an e format.

     long
          Octave will try to print numbers with at least 15 significant figures within a field that is a maximum of 20 characters wide (not counting additional spacing that is added between columns of a matrix).

          As will the short format, Octave will switch to an e format if it is unable to format a matrix so that columns line up on the decimal point and all the numbers fit within the maximum field width.

     long e
     short e
          The same as format long or format short but always display output with an e format.  For example, with the short e format, pi is displayed as 3.14e+00.

     long E
     short E
          The same as format long e or format short e but always display output with an uppercase E format.  For example, with the long E format, pi is displayed as 3.14159265358979E+00.

     long g
     short g
          Choose between normal long (or short) and and long e (or short e) formats based on the magnitude of the number.  For example, with the short g format, pi .^ [2; 4; 8; 16; 32] is displayed as

               ans =

                     3.1416
                     9.8696
                     97.409
                     9488.5
                 9.0032e+07
                 8.1058e+15

     long G
     short G
          The same as format long g or format short g but use an uppercase E format.  For example, with the short G format, pi .^ [2; 4; 8; 16; 32] is displayed as

               ans =

                     3.1416
                     9.8696
                     97.409
                     9488.5
                 9.0032E+07
                 8.1058E+15

     free
     none
          Print output in free format, without trying to line up columns of matrices on the decimal point.  This also causes complex numbers to be formatted like this (0.604194, 0.607088) instead of like this 0.60419 + 0.60709i.

     bank
          Print in a fixed format with two places to the right of the decimal point.

     +
     + CHARS
     plus
     plus CHARS
          Print a + symbol for nonzero matrix elements and a space for zero matrix elements.  This format can be very useful for examining the structure of a large matrix.

          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, [1, 0, -1; -1, 0, 1] is displayed as

               ans =

               +.-
               -.+

     native-hex
          Print the hexadecimal representation numbers as they are stored in memory.  For example, on a workstation which stores 8 byte real values in IEEE format with the least significant byte first, the value of pi when printed in hex format is 400921fb54442d18. This format only works for numeric values.

     hex
          The same as native-hex, but always print the most significant byte first.

     native-bit
          Print the bit representation of numbers as stored in memory. For example, the value of pi is

               01000000000010010010000111111011
               01010100010001000010110100011000

          (shown here in two 32 bit sections for typesetting purposes) when printed in bit format on a workstation which stores 8 byte real values in IEEE format with the least significant byte first.  This format only works for numeric types.

     bit
          The same as native-bit, but always print the most significant bits first.

     compact
          Remove extra blank space around column number labels.

     loose
          Insert blank lines above and below column number labels (this is the default).

     By default, Octave will try to print numbers with at least 5 significant figures within a field that is a maximum of 10 characters wide.

     If Octave is unable to format a matrix so that columns line up on the decimal point and all the numbers fit within the maximum field width, it switches to an e format.

     If format is invoked without any options, the default format state is restored.

 -- Built-in Variable: print_answer_id_name
     If the value of print_answer_id_name is nonzero, variable names are printed along with the result.  Otherwise, only the result values are printed.  The default value is 1.

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.

 -- Built-in Function: input (PROMPT)
 -- Built-in Function: input (PROMPT, "s")
     Print a 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 expression.

     Currently, input only returns one value, regardless of the number of values produced by the evaluation of the expression.

     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.  See Input and Output.

 -- Function File: menu (TITLE, OPT1, ...)
     Print a title string followed by a series of options.  Each option will be printed along with a number.  The return value is the number of the option selected by the user.  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.

disp, printf, and input

 -- Built-in Function: keyboard (PROMPT)
     This function is normally used for simple debugging.  When the keyboard function is executed, Octave prints a prompt and waits for user input.  The input strings are then evaluated and the results are printed.  This makes it possible to examine the values of variables within a function, and to assign new values to variables.  No value is returned from the keyboard function, and it continues to prompt for input until the user types quit, or exit.

     If keyboard is invoked without any arguments, a default prompt of debug>  is used.

For both input and keyboard, 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.

 -- Built-in Function: kbhit ()
     Read a single keystroke from the keyboard. If called with one argument, don't wait for a keypress.  For example,

          x = kbhit ();

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

          x = kbhit (1);

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

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 built-in variables default_save_format and save_precision.

Note that Octave cannot yet save or load structure variables or any user-defined types.

 -- Command: save options file v1 v2 ...
     Save the named variables V1, V2, ... in the file FILE.  The special filename - can be used to write the output to your terminal.  If no variable names are listed, Octave saves all the variables in the current scope.  Valid options for the save command are listed in the following table.  Options that modify the output format override the format specified by the built-in variable default_save_format.

     -ascii
          Save the data in Octave's text data format.

          WARNING: the meaning of this option will change in a future version of Octave to be compatible with MATLAB.  To keep the meaning of your code the same across this change, use the -text option instead.

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

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

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

     -V4
     -v4
     -4
     -mat4-binary
          Save the data in the binary format written by MATLAB version 4.

     -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.)

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

     -save-builtins
          Force Octave to save the values of built-in variables too.  By default, Octave does not save built-in variables.

     The list of variables to save may include wildcard 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 upper case alphabetic characters.

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

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

     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.

There are three variables that modify the behavior of save and three more that control whether variables are saved when Octave exits unexpectedly.

 -- Built-in Variable: crash_dumps_octave_core
     If this variable is set to a nonzero value, Octave tries to save all current variables the the file "octave-core" if it crashes or receives a hangup, terminate or similar signal.  The default value is 1. octave_core_file_limit, octave_core_file_name, and octave_core_file_format

 -- Built-in Variable: sighup_dumps_octave_core
     If this variable is set to a nonzero value and crash_dumps_octave_core is also nonzero, Octave tries to save all current variables the the file "octave-core" if it receives a hangup signal.  The default value is 1.

 -- Built-in Variable: sigterm_dumps_octave_core
     If this variable is set to a nonzero value and crash_dumps_octave_core is also nonzero, Octave tries to save all current variables the the file "octave-core" if it receives a terminate signal.  The default value is 1.

 -- Built-in Variable: default_save_format
     This variable specifies the default format for the save command. It should have one of the following values: "ascii", "binary", float-binary, or "mat-binary".  The initial default save format is Octave's text format.

 -- Built-in Variable: save_precision
     This variable specifies the number of digits to keep when saving data in text format.  The default value is 17.

 -- Built-in Variable: save_header_format_string
     This variable specifies the the format string for the comment line that is written at the beginning of text-format data files saved by Octave.  The format string is passed to strftime and should 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>"

     strftime

 -- Command: load options file v1 v2 ...
     Load the named variables from the file FILE.  As with save, you may specify a list of variables and load will only extract those variables with names that match.  For example, to restore the variables saved in the file data, use the command

          load data

     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.  Since it seems that both of these cases are likely to be the result of some sort of error, they will generate warnings.

     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.  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 added in the future).

     Valid options for load are listed in the following table.

     -force
          The -force option is accepted but ignored for backward compatiability. Octave now overwrites variables currently in memeory with the same name as those found in the file.

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

          WARNING: the meaning of this option will change in a future version of Octave to be compatible with MATLAB.  To keep the meaning of your code the same across this change, use the -text option instead.

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

     -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 the binary format written by MATLAB version 4.

     -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 Octave can read HDF5 files not created by itself, but may skip some datasets in formats that it cannot support.

     -import
          The -import is accepted but ignored for backward compatiability. 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.

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 file name 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.

 -- Built-in Variable: stdin
     The standard input stream (file id 0).  When Octave is used interactively, this is filtered through the command line editing functions.

 -- Built-in Variable: stdout
     The standard output stream (file id 1).  Data written to the standard output is normally filtered through the pager.

 -- Built-in Variable: stderr
     The standard error stream (file id 2).  Even if paging is turned on, the standard error is not sent to the pager.  It is useful for error messages and prompts.

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

 -- Built-in Function: [FID, MSG] = fopen (NAME, MODE, ARCH)
 -- Built-in Function: FID_LIST = fopen ("all")
 -- Built-in Function: FILE = fopen (FID)
     The first form of the fopen function opens the named file with the specified mode (read-write, read-only, etc.) and architecture interpretation (IEEE big endian, IEEE little endian, etc.), 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 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 the name of a currently 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 mode may have are

     r
          Open a file for reading.

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

     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 and Macintosh systems, text mode reading and writing automatically converts linefeeds to the appropriate line end character for the system (carriage-return linefeed on Windows, carriage-returnn on Macintosh).  The default if no mode is specified is binary mode.

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

          native The format of the current machine (this is the default).

          ieee-be IEEE big endian format.

          ieee-le IEEE little endian format.

          vaxd VAX D floating format.

          vaxg VAX G floating format.

          cray Cray floating format.

     however, conversions are currently only supported for native ieee-be, and ieee-le formats.

fclose, fread, fseek

 -- Built-in Function: fclose (FID)
     Closes the specified file.  If successful, fclose returns 0, otherwise, it returns -1.

fopen, fseek, ftell

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

 -- Built-in Function: fputs (FID, STRING)
     Write a string to a file with no formatting.

     Return a non-negative number on success and EOF on error.

 -- Built-in Function: puts (STRING)
     Write a string to the standard output with no formatting.

     Return a non-negative number on success and EOF on error.

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

 -- Built-in Function: 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.

fread, fscanf

 -- Built-in Function: 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.

fread, fscanf

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

This section describes how to call printf and related functions.

The following functions are available for formatted output.  They are modelled 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.

 -- Built-in Function: printf (TEMPLATE, ...)
     Print optional arguments under the control of the template string TEMPLATE to the stream stdout.

     Return the number of characters printed.

fprintf, sprintf, scanf

 -- Built-in Function: fprintf (FID, TEMPLATE, ...)
     This function is just like printf, except that the output is written to the stream FID instead of stdout.

printf, sprintf, fread, fscanf, fopen, fclose

 -- Built-in Function: 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.

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 ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
             filename, pct);

produces output like

     Processing of `foo.txt' is 37% finished.
     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 lower-case letters and %X uses upper-case.  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 lower-case letters and %E uses upper-case.  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 lower-case letters and %G uses upper-case. 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.  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'.

 -- Built-in Function: [VAL, COUNT] = fscanf (FID, TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT] =  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.

     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

scanf, sscanf, fread, fprintf

 -- Built-in Function: [VAL, COUNT] = sscanf (STRING, TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT] =  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.

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.

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.

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 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.

Unlike the C language scanf, Octave ignores the h, l, and L modifiers.

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.  The are able to automatically swap the byte order of integer data and convert among ths supported floating point formats as the data are read.

 -- Built-in Function: [VAL, COUNT] = fread (FID, SIZE, PRECISION, SKIP, ARCH)
     Read binary data of type PRECISION from the specified file ID 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

     "schar"
     "signed char"
          Signed character.

     "uchar"
     "unsigned char"
          Unsigned character.

     "int8"
     "integer*1"

          8-bit signed integer.

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

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

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

     "uint8"
          8-bit unsigned integer.

     "uint16"
          16-bit unsigned integer.

     "uint32"
          32-bit unsigned integer.

     "uint64"
          64-bit unsigned integer.

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

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

     "char"
     "char*1"
          Single character.

     "short"
          Short integer (size is platform dependent).

     "int"
          Integer (size is platform dependent).

     "long"
          Long integer (size is platform dependent).

     "ushort"
     "unsigned short"
          Unsigned short integer (size is platform dependent).

     "uint"
     "unsigned int"
          Unsigned integer (size is platform dependent).

     "ulong"
     "unsigned long"
          Unsigned long integer (size is platform dependent).

     "float"
          Single precision floating point number (size is platform dependent).

     The default precision is "uchar".

     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, 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"
          The format of the current machine.

     "ieee-be"
          IEEE big endian.

     "ieee-le"
          IEEE little endian.

     "vaxd"
          VAX D floating format.

     "vaxg"
          VAX G floating format.

     "cray"
          Cray floating format.

     Conversions are currently only supported for "ieee-be" and "ieee-le" formats.

     The data read from the file is returned in VAL, and the number of values read is returned in count

fwrite, fopen, fclose

 -- Built-in Function: COUNT = fwrite (FID, DATA, PRECISION, SKIP, ARCH)
     Write data in binary form of type PRECISION to the specified file ID FID, returning the number of values successfully written to the file.

     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 behavior of fwrite is undefined if the values in DATA are too large to fit in the specified precision.

fread, fopen, fclose

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

 -- Built-in Function: [FID, NAME, MSG] = mkstemp (TEMPLATE, DELETE)
     Return the file ID 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 with the O_EXCL flag.

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

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

tmpfile, tmpnam, and P_tmpdir

 -- Built-in Function: [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. The file 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.

tmpnam, mkstemp, and P_tmpdir

 -- Built-in Function: tmpnam (DIR, PREFIX)
     Return a unique temporary file name as a string.

     If PREFIX is omitted, a value of "oct-" is used. If DIR is also omitted, the default directory for temporary files is used.  If DIR is provided, it must exist, otherwise the default directory for temporary files is used.  Since the named file is not opened, by tmpnam, it is possible (though relatively unlikely) that it will not be available by the time your program attempts to open it.

tmpfile, mkstemp, and P_tmpdir

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

 -- Built-in Function: feof (FID)
     Return 1 if an end-of-file condition has been encountered for a given file and 0 otherwise.  Note that it 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, fopen, fclose

 -- Built-in Function: ferror (FID)
     Return 1 if an error condition has been encountered for a given file and 0 otherwise.  Note that it will only return 1 if an error has already been encountered, not if the next operation will result in an error condition.

 -- Built-in Function: 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  name
               -|
               -|       0     r  stdin
               -|       1     w  stdout
               -|       2     w  stderr
               -|       3     r  myfile

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

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

 -- Built-in Function: ftell (FID)
     Return the position of the file pointer as the number of characters from the beginning of the file FID.

fseek, fopen, fclose

 -- Built-in Function: fseek (FID, OFFSET, ORIGIN)
     Set the file pointer to any location within the file FID.

     The pointer is positioned OFFSET characters from the ORIGIN, which may be one of the predefined variables SEEK_CUR (current position), SEEK_SET (beginning), or SEEK_END (end of file) or strings "cof", "bof" or "eof". If ORIGIN is omitted, SEEK_SET is assumed.  The offset must be zero, or a value returned by ftell (in which case ORIGIN must be SEEK_SET.

     Return 0 on success and -1 on error.

ftell, fopen, fclose

 -- Built-in Variable: SEEK_SET
 -- Built-in Variable: SEEK_CUR
 -- Built-in Variable: SEEK_END
     These variables may be used as the optional third argument for the function fseek.

     SEEK_SET
          Position file relative to the beginning.

     SEEK_CUR
          Position file relative to the current position.

     SEEK_END
          used with fseek to position file relative to the end.

 -- Built-in Function: frewind (FID)
     Move the file pointer to the beginning of the file FID, returning 0 for success, and -1 if an error was encountered.  It is equivalent to fseek (FID, 0, SEEK_SET).

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);