Next: Writing to a file
Up: File I/O
Previous: File I/O

Reading from a file

Suppose that we'd like to write a program that reads ten numbers from a file, adds them up, and prints the result to the display. Take a look at ``file1.f'' in your ``examples'' directory (or view it directly).

The program in this file reads ten (one or two digit) integers from the keyboard and then prints out their sum. Run it---but don't forget to enter the numbers. It doesn't remind you to enter them!

Now compare ``file2.f'' (or view it directly) to ``file1.f''. What are the differences?

Click here for the answer

That's the only basic difference between reading from the keyboard and reading from a file. You simply use an OPEN statement to associate a unit number with a file. (You can use any unit number that you please.)

Now compile and run the program. What happens?

Click here for the answer

To make the program work, you need to create a file (using Emacs) containing ten one or two digits numbers, each on a different line. When you have done this, place its name into the program in place of 'filename'. Be sure that your file is in the same directory as the program.

Make sure that the modified program runs properly before moving on.


Next: Writing to a file
Up: File I/O
Previous: File I/O

Hamlet Project
hamlet@cs.utah.edu