User Input/Output

Using the write statement, we can output text to the screen:

! hello.f90
program main
    write (*, *) 'Hello, World!'
end program main

The two asterisks set the output unit and the format to default. The output unit can be either changed to standard output, a file, or a variable. The output format may be customised by a format list, similiar to printf in other programming languages. The above command is equal to write (unit=*, fmt=*) 'Hello, World!' and print *, 'Hello, World!'.

You can compile the example with the GNU Fortran:

$ gfortran10 -o hello hello.f90

Or, using the Flang compiler:

$ flang -o hello hello.f90

Then, execute the compiled binary to see the output:

$ ./hello
 Hello, World!

You may notice a space character before the printed text. In the old days, the first column of all output was reserved for carriage control. To remove the leading space, simply add a format specifier:

write (*, '(a)') 'Hello, World!'

Or, shorter:

print '(a)', 'Hello, World!'

Formatted Input/Output

The input and output is formatted with format edit descriptors.

Format Description
"string" Inserts string.
Iw[.m] Read/Write w characters as integer number, with optional number of leading zeros m.
Bw[.m] Read write w characters as binary values, with optional number of leading zeros m.
Ow[.m] Read write w characters as octal values, with optional number of leading zeros m.
Zw[.m] Read write w characters as hexadecimal values, with optional number of leading zeros m.
Fw.d Read/Write fixed-point number with w digits, of which d is the number of decimal places. Sign and floating point must be regarded in w. F0.d allows a variable length.
Ew.d Read/Write Floating-point number with w digits, of which d is the number of decimal places. Sign and floating point must be regarded in d.
Dw.d Read/Write Floating-point number, double precision.
A, Aw. Read/Write arbitrary length string, or string with w characters
Lw Read/Write w characters as logical.
nx Read: Ignore the next n characters.
Write: Print n spaces.
Tc Next character at position c.
/ Line feed.

The Hollerith constant H is deprecated and should not be used anymore. Format specifiers can be written in upper or lower case. Multiple format specifiers are separated by comma, for example, (a, i3, a) to output 'total: ', 420, ' units'. Strings may be written inside the format specifier:

print '("total: ", i3, " units")', 420

Format specifiers can be grouped and repeated using parentheses:

print '(2(a, i2))', 'A: ', 10, 'B: ', 20

We can reuse format specifiers by storing them in a string:

character(len=*), parameter :: F = '(2(a, i2))'

print F, 'A: ', 10, 'B: ', 20
print F, 'A: ', 20, 'B: ', 40
print F, 'A: ', 30, 'B: ', 80