Exercise: Fortran Basics, IO
We will create the traditional "Hello, World" program, compile it and execute it. In each of these exercises, use your favorite text editor and save the files with names ending with .f90
(as we will be using free format)
Once the file is saved, compile your program and run it (it will have been created with executable permission):
Now we will produce a program to take some input and write it to a file. Note that here we impose a limit on the length of the input in declaring the string (although there are options in Fortran 95 for non-advancing input, and Fortran 2003 allows deferred specification of character variables).
Compile and run:
Now we will go back and edit writeFile.f90
to actually write to a file (remember to compile again after editing!)
Open the file myOutputFile.txt
and look inside it; you should see your input! Note that the string contains enough trailing spaces to take it up to 50 total characters. Edit writeFile.f90
so that the write
line is:
Recompile, run it again and check for trailing spaces (they should be gone). Now open myOutputFile.txt
and add in a few more words on the same line, but staying within 50 characters total, including spaces.
Next we will read from our file and output the contents to standard output.
You should see the whole of the text line from myOutputFile.txt
, including your additions, written out to your screen. Notice that the syntax one uses for files and standard I/O is very similar, in read
statements as well as write
statements.