This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Session 12: File operations [June 11, 2011, 12:37 p.m.]


Objectives

In this session we will learn the following:

  1. Writing formatted output to Scilab console
  2. Reading data from files into Scilab variables
  3. Writing formatted output to a file

Functions Used

mopen(), mprintf(), mfprintf(), msprintf(), mfscanf(), msscanf()

Introduction

Scilab file operations are similar to those in C programming language. If you are familiar with file operations in C, you will find it easy to perform file operations in Scilab. But this session does not assume you know C.

For both input and output, you will find a set of three similar functions - output to standard output (or input from standard input), output to (or input from) a file and output to (or input from) a string.

To write to (or read from) a file, it is necessary to first open the file for writing (or reading), perform the write (or read) operations and finally close the file.

Output Functions

Output to Standard Output (Scilab Console)

Let us first write scalar values first and then see how to write matrices.

-->mprintf("%5d, %12.3f\n", 120, 1234.55)
  120,     1234.55

Notice what happened:

  1. To the function mprintf(), we provided three arguments. First, a string containing formatting specifications ("%5d, %12.3f\n"). Second is an integer (120). Third is a real number (1234.55)
  2. The formatting specification contains two format placeholders, namely, %5d and %12.3f. Format placeholders begin with the %. Rest of the formatting specification string are output as they are.
  3. %5d corresponds to the second argument to mprintf(), namely 120. It outputs 120 as an integer (%d), formatting it is a width of 5 places (%5d)
  4. %12.3f can be understood as follows - 12 is the width, 3 is the precision (number of decimal places) and f corresponds to a float (real number).
  5. If there are two placeholders in the formatting specification string, it must be followed by two values with the matching data type as in the formatting specification.

To print out values of a matrix, the format specification string must be able to print one full row of the matrix. This specification will be used for each row of the matrix until all rows are printed. Let us see an example:

-->a = [1 2 3 4; 5 6 7 8];
-->mprintf("%5.2f,%5.2f,%5.2f,%5.2f\n", a)
 1.00, 2.00, 3.00, 4.00
 5.00, 6.00, 7.00, 8.00