A few words about files

In the assignment you need to read from a file and store the results on another file. Here are a few ways to do it.

When using unix you can use the redirection of stdin and stdout (standard input, standard output). So if a program, in the normal case, reads from, and writes to the terminal window, you can do like this, instead:

a.out < infile > outfile

The program will read from infile and write on outfile instead. This is very practical when using ordinary unix-commands as well, e.g. command > file, command < file or (using pipes) command1 | command2 | command3 > file etc.

Redirection may be inconvenient if you need to write (or read) to more than one file. Some shells (like bash) can split the output to different files (provided the program is written in a special way). If, for example, a program writes its ordinary output to stdout and error messages to stderr, one can split the output. Standard output has file descriptor 1 and standard error has 2.

The command: command 1> file_std 2> file_err (or shorter command > file_std  2> file_err) will write its standard output on file file_std and the error output on file_err. For more details, give the command man bash or info bash .

In many situations you do not want to use redirection. The program may be is using many files or files unknown to the user of the program. The standard technique, in both Fortran and C, is to connect the filename (in the filesystem) with an internal number, unit, descriptor or pointer (terminology varies) in the program.

The codes below read a file containg twenty lines, where each line contains an integer and a floating point variable. The numbers are stored in two arrays. In the first part of the program we assume we know the file consist of twenty line. And the second part we read until the read-statement encounters end-of-file. Note that we must have allocated enough elements in the arrays for this solution to work. Reading more than twenty lines, storing the elements in the too short arrays, is an error.

Fortran90, Fortran77 and C. Note that you have to adjust these programs to fit the assignment.


Back