Creative Commons License Copyright © Michael Richmond. This work is licensed under a Creative Commons License.

Reading and writing data in files

It is often very useful to store data in a file on disk for later reference. But how does one put it there, and how does one read it back? Each programming language has its own peculiar convention. Scilab provides several different functions that can be used to write and read data, each of which is designed for a particular situation. In this lesson, I will describe one method: not the most efficient one, certainly, but one which will look very similar in several other programming languages. If you learn to use this style, you can very easily adapt it to other environments.

In the examples below, the data file is a simple one: it contains several columns of ASCII characters, with the same number of columns on each line, like this:

     1         2       3.5
     2         4       7
     3         6      10.5
     4         8      14

This multi-column format is very common -- even spreadsheets can read and write it.


Reading multicolumn data

Let's break the task down into several steps.

  1. Open the file for reading

  2. Read the next line

  3. Close the file

Step 1 typically occurs near the start of a program, step 2 inside a loop, and step 3 at the very end. Let's look at each one in some detail.


Writing multicolumn data

Let's break the task down into several steps.

  1. Open the file for writing

  2. Write the next line

  3. Close the file

Step 1 typically occurs near the start of a program, step 2 inside a loop, and step 3 at the very end. Let's look at each one in some detail.


Examples

You can find some examples of short, simple Scilab programs which read and write information from and to files in the examples section of the course WWW site. Specifically,


Practice in class


Last modified 4/17/2007 by MWR

Creative Commons License Copyright © Michael Richmond. This work is licensed under a Creative Commons License.