Writing Files in Fortran
Here’s the translation of the Go code to Fortran, along with explanations in Markdown format suitable for Hugo:
Writing files in Fortran follows similar patterns to the ones we saw earlier for reading.
Let’s break down the Fortran code and explain the key concepts:
We start by defining our program and importing necessary modules. The
iso_fortran_env
module provides access to environment-specific constants and procedures.We define the filenames as parameters and declare variables for file units, I/O status, and error messages.
To write a simple string to a file, we use the
open
statement withstatus='replace'
to create or overwrite the file, andaction='write'
to specify write-only access.We use
write
statements to output strings to the file. The format specifier'(A)'
is used for character data.After writing, we close the file using the
close
statement.For more granular writes, we open another file in a similar manner.
We can write character data directly using
write
statements.Fortran performs buffered I/O by default, but we can use the
flush
statement to ensure all data is written to the file immediately.Finally, we close the file to ensure all data is written and resources are released.
To run the file-writing code, compile and execute the Fortran program:
Then check the contents of the written files:
In Fortran, file I/O is handled through unit numbers and the open
, write
, and close
statements. While it doesn’t have a direct equivalent to Go’s bufio
package, Fortran’s built-in I/O is typically buffered for efficiency. The flush
statement can be used to ensure all data is written to the file.
Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the standard input and output streams.