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 10, 2011, 11:07 a.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.