Once we have the desired filename stored in the filename variable, our next step is to open the file for writing. Opening a file means creating a connection between the program and some file on disk. We can do this using the open statement:
open(newunit=fileunit, file=trim(filename)) ❶
❶ Opens a file with a given filename, assigning its I/O unit to fileunit
This is one of the most basic forms of the open statement. It takes two keyword arguments:
newunit–An integer variable whose value will be set to an available I/O unit number. This number is system-dependent and not known ahead of time, but is guaranteed to be available and not conflict with any other units, be it other open files or standard streams such as stdout or stderr.file–A character variable or literal constant whose value is the name of the file to open.
On successful execution of this open statement, the new file is now open and ready for use, with a unique I/O unit number assigned to fileunit. Once a file is opened and attached to a unit, it can’t be opened again before it’s closed and its I/O unit is released. Alternatively, you can pass the unit number to the open statement yourself, but you have to make sure that I/O unit is available for use:
open(unit=2112, file=trim(filename))
With this statement, a file is opened, and the unit number 2112 is assigned to it. Note that spelling out unit= is optional but file= is not, so you can just write open(2112, file=trim(filename)) for brevity. Historically, a Fortran programmer was expected to keep track of the I/O units being used. It’s important to be aware of this form of the open statement because you’re likely to encounter it in Fortran code in the wild, as the newunit functionality was added to the language only recently (Fortran 2008). If your compiler supports it, and a recent version of any mainstream compiler should, I recommend that you use newunit exclusively.
Tip Use newunit in your open statements rather than specifying the unit number yourself. It will spare you from having to keep track of available I/O units.
There may be exceptional situations where you’d need to specify an I/O unit in the open statement, rather than getting a new one from the system. One such situation is if you wanted to redirect standard output and error channels to files. Let’s do this one as an exercise. (See “Exercise” sidebar.)
Exercise: Redirect stdout and stderr to files
You now know how to access standard output and error I/O units, and you know how to open files with a specific I/O unit number. Write a program that redirects its standard output and error into files; for example, log.out and log.err, respectively.
You can find the solution to this exercise in the “Answer key” section near the end of this chapter.