Input and Output

There are two types if I/O in RLaB  .

  1. Raw data, such as matrices, lists, and strings. In this case the formatting is irrelevant.
  2. Formatted I/O, such as data from other programs, and formatted output intended for reports and such.

In either case file names, or file-handles, are the same. A file-handle is always a string, either a string constant, a string variable, or a string expression. For example:

> write ("file.rd", A);

> f = "file.rd"; write (f, A);

> write ("file" + ".rd", A);

are all equivalent.

There are three special file-handles in RLaB  ; they are: "stdin", "stdout", and "stderr".

"stdin" is connected to RLaB 's standard input, usually the keyboard. "stdout" is connected to RLaB 's standard output, usually the screen. And "stderr" is connected to the standard error, again, usually the screen.

Files are automatically opened by the functions that perform input or output. In most cases the files will automatically be closed after the function has completed its task. The following will force a file closure after their task is complete: rfile, load, read, and readm.

However, write, writem, fprintf, and getline will leave their files open after completion, so that they may be used subsequently without complicated file positioning operations.

RLaB  has another special type of file-handle. When a string, starting with a `|' is used as a file-handle, a process is created. Either the sub-process input, or output is connected to RLaB  through the file-handle. For example:

> output = "| sort";
> for (i in 5:1:-1) { fprintf (output, "%i\n", i); } close (output);
1
2
3
4
5

If the fprintf output were not sent to the Unix program sort, you would expect the output to appear in descending order. In fact, fprintf does write the output in descending order, to sort. Then, sort re-orders its input, and writes it to stdout. The same trick works in reverse; functions that expect input can get it from a sub-process. A good example is getline:

> input = "| ls -la *.[ch]";
> fsum = 0;
> while (length (ans = getline (input))) { fsum = fsum + ans.[5]; } fsum
 fsum =
   943083
> close (input);

In this instance we used the sub-process capability to determine the number of bytes of C source code, and header files exist in the current working directory. The sub-process performs the long listing, and getline parses this input into numbers and strings. The 5th column of the ls -la output is the number of bytes in each file.