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. The C-style I/O functions offer more flexibility and control over the output, but are not quite as easy to use as the simpler MATLAB-style I/O functions.
When running interactively, Octave normally sends any output intended
for your terminal that is more than one screen long to a paging program,
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) it also allows you to
scan forward and backward, and search for specific items.
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
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 immediately. See section C-Style I/O Functions.
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
page_screen_output to 0.
"less", or, if
lessis not available on your system,
"more". See section Installing Octave.
page_screen_outputis 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 section Installing Octave) are also capable of moving backward on the output. The default value is 1.
page_output_immediatelyis 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.
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
octave:13> 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
format command offers some control over the way Octave prints
disp and through the normal echoing mechanism.
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.
dispand Octave's normal echoing mechanism. Valid options are listed in the following table.
piwhen printed in
400921fb54442d18. This format only works for numeric values.
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.
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.
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
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 section C-Style I/O Functions.
keyboardfunction 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
keyboardfunction, and it continues to prompt for input until the user types `quit', or `exit'.
keyboard is invoked without any arguments, a default prompt of
`debug> ' is used.
keyboard, the normal command line
history and editing functions are available at the prompt.
load commands allow data to be written to and
read from disk files in various formats.
savecommand are listed in the following table.
default_save_format. You should use this format only if you know that all the values to be saved can be represented in single precision.
The list of variables to save may include wildcard patterns containing the following special characters:
[ list ]
^, match all characters except those specified by list. For example, the pattern `[a-zA-Z]' will match all lower and upper case alphabetic characters.
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.
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 two variables that modify the behavior of
savecommand. It should have one of the following values:
"mat-binary". The initial default save format is Octave's text format.
loadcommand. As with
save, you may specify a list of variables and
loadwill only extract those variables with names that match. For example, to restore the variables saved in the file `data', use the command
Octave will refuse to overwrite existing variables unless you use the option `-force'.
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.
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.
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 either to an integer file number (as returned by `fopen') or a file name.
There are three files that are always available:
You should always use the symbolic names given in the table above, rather than referring to these files by number, since it will make your programs clearer.
myfile = fopen ("splat.dat", "r");
opens the file `splat.dat' for reading. Opening a file that is already open has no effect.
The possible values `mode' may have are
fclosereturns 0. Otherwise, it returns 1.
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.
printffunction prints the optional arguments under the control of the template string template to the stream
printf, except that the output is written to the stream fid instead of
printf, except that the output is written to a string. Unlike the C library function, which requires you to provide a suitably sized string as an argument, Octave's
sprintffunction returns the string, automatically sized to hold all of the items converted.
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.
This section provides details about the precise syntax of conversion
specifications that can appear in a
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:
printffunction, but is recognized to provide compatibility with the C language
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.
Here is a table summarizing what all the different conversions do:
scanffor input (see section Table of Input 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.
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:
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.
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
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
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:
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
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.
This section describes miscellaneous conversions for
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");
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 '.
Here are the descriptions of the functions for performing formatted input.
scanffunction reads formatted input from the stream
stdinunder the control of the template string template. The resulting values are returned.
scanf, except that the input is read from the stream fid instead of
scanf, 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.
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
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
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.
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:
scanffinds 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 use a pointer argument, and does not increment the count of successful assignments.
scanffunction, but is recognized to provide compatibility with the C language
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.
Here is a table that summarizes the various conversion specifications:
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.
This section describes the
scanf conversions for reading numeric
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
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.
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:
with the conversion `%10c' produces
" hello, wo", but
reading the same input with the conversion `%10s' produces
Octave has to C-style functions for reading and writing binary data.
fwrite and are patterned after the
standard C functions with the same names.
The argument size specifies the size of the matrix to return. It
may be a scalar or a two-element vector. If it is a scalar,
fread returns a column vector of the specified length. If it is
a two-element vector, it specifies the number of rows and columns of the
result matrix, and
fread fills the elements of the matrix in
The argument precision is a string specifying the type of data to
read and may be one of
default precision is
fread function returns two values,
data, which is the
data read from the file, and
count, which is the number of
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 argument precision is a string specifying the type of data to
read and may be one of
default precision is
fwrite function returns the number of elements written.
The behavior of
fwrite is undefined if the values in data
are too large to fit in the specified precision.
Three functions are available for setting and determining the position of the file pointer for a given file.
offsetcharacters from the
origin, which may be one of the predefined variables
SEEK_END(end of file). If
SEEK_SETis assumed. The offset must be zero, or a value returned by
ftell(in which case
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);
x = kbhit ();
will set x to the next character typed at the keyboard, without requiring a carriage return to be typed.
freportprints this information for all open files. For example,
octave:13> freport number mode name 0 r stdin 1 w stdout 2 w stderr 3 r myfile
Go to the first, previous, next, last section, table of contents.