Fortran

Guide To Learn

Opening files in read-only or write-only mode

Sooner or later, you’ll run across files that are meant to be used as read-only; for example, important satellite data that shouldn’t be overwritten. Similarly, some files will be useful only in write-only mode, such as the quick notes that we’ve been working on in this section. Fortran allows you to open a file in a mode that restricts certain operations to a file. Here’s an example of opening a file in read-only mode:

open(newunit=fileunit, file=trim(filename), action='read')

The read/write behavior is controlled with the action keyword parameter. It can take one of three values:

  • read–The file will be opened in read-only mode, and write and print statements can’t be used on this file. Furthermore, the file will be assumed to be existing, so it’s impossible to open new files when using action='read'.
  • write–The file will be opened in write-only mode, and the read statement can’t be used in connection with this file.
  • readwrite–The file is opened without restriction. This is also the default behavior (if action is not specified) on all the systems that I’m aware of; however, the Fortran Standard allows this to be system-dependent.

Why do this? If the file is supposed to be read-only, can we simply not issue any write statements and be done with it? Likewise for write-only files. You don’t ever have to use the action parameter to write correct Fortran programs. However, it may be beneficial to do so for at least two reasons. First, if you’re working with a read-only file, specifying action='read' in the open statement will prevent you from accidentally writing to it elsewhere in the program, either because of a typo or by confusing two different I/O units. Second, your code will be easier to read and understand. This is analogous to my advice from chapter 3 about always specifying intent for procedure arguments. It’s easier to understand what the program is doing to a file if the open statement says it loud and clear.

Tip Always specify action in your open statements. It will make your code easier to understand and can prevent you from accidentally overwriting important files.

You can go ahead and update the open statement in our quick-note program to read

open(newunit=fileunit, file=trim(filename),&
     action='write', position='append')

While not strictly necessary, it’s good practice and will help future readers of your code (including yourself).

Opening files in read-only or write-only mode

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top