Writing Files in Co-array Fortran
Here’s the translation of the Go code to Co-array Fortran, formatted in Markdown suitable for Hugo:
Our first example demonstrates how to write files in Co-array Fortran. Writing files follows similar patterns to reading files.
This program demonstrates various ways to write files in Co-array Fortran:
We start by writing a string directly to a file using a custom subroutine
write_file
.Then, we open a file for more granular writes. In Fortran, it’s common to use the
open
statement withnewunit
to get a new unit number automatically.We write byte values to the file using the
char
function to convert integers to characters.We demonstrate writing a string directly to the file.
The
flush
statement is used to ensure all buffered data is written to the file.Finally, we show another string write, which could be considered a “buffered” write in the context of Fortran’s I/O system.
We close the file explicitly at the end.
To run this program:
Then check the contents of the written files:
Note that Co-array Fortran doesn’t have a direct equivalent to Go’s bufio
package for buffered I/O. Fortran’s I/O system handles buffering internally, and the flush
statement can be used to ensure data is written to the file.
Next, we’ll look at applying some of these file I/O ideas to standard input and output streams.