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

(disp)

(list_in_columns)

(terminal_size)

(format)

Paging Screen 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 using the PAGER function, and you can turn paging off by using the function more.

(more)

(PAGER)

(PAGER_FLAGS)

(page_screen_output)

(page_output_immediately)

(fflush)

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.

(input)

(menu)

(yes_or_no)

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.

(kbhit)

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

(load)

(fileread)

There are three functions that modify the behavior of save.

(default_save_options)

(save_precision)

(save_header_format_string)

(native_float_format)

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)

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

(dlmwrite)

(dlmread)

(csvwrite)

(csvread)

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

(textread)

(textscan)

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

(crash_dumps_octave_core)

(sighup_dumps_octave_core)

(sigterm_dumps_octave_core)

(octave_core_file_options)

(octave_core_file_limit)

(octave_core_file_name)

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.

(stdin)

(stdout)

(stderr)

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

(fopen)

(fclose)

(is_valid_file_id)

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

(fputs)

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.

(puts)

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.

(fgetl)

(fgets)

(fskipl)

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.

(printf)

(fprintf)

(sprintf)

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

(fscanf)

(scanf)

(sscanf)

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

(fread)

(fwrite)

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.

(mkstemp)

(tmpfile)

(tmpnam)

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.

(feof)

(ferror)

(fclear)

(freport)

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

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

(ftell)

(fseek)

(SEEK_SET)

(frewind)

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