Fortran

Guide To Learn

OK, so we’ve parsed the command line for a filename as the argument, and we’ve opened the file as requested by the user. Let’s write some notes to it. To do this, we’ll need to parse user input from the keyboard, and write the data to the file on each new line–that is, every time the user presses the Enter or Return key. The following listing demonstrates this.

Listing 6.8 Reading user input and writing to a file in a loop

do                                       ❶
  read(stdin, '(a)') text                ❷
  write(fileunit, '(a)') trim(text)      ❸
  flush(fileunit)                        ❹
end do

❶ Loops indefinitely

❷ Reads a single line from standard input and stores it into text

❸ Writes text into the file connected to fileunit, removing any trailing whitespace

❹ Flushes the write buffer to file

We use a plain do statement to loop indefinitely. Within each iteration, the program reads the user’s input from the console, trims any trailing whitespace (because text is 9,999 characters long), and writes it to the file. On each write, we use the flush statement to make sure that any data from the buffer is written to disk. The program doesn’t have any way to exit the loop, except by hitting an exception in one of the I/O statements (for example, running out of disk space), or by the user quitting the program with a keyboard interrupt (Ctrl+C). For our little app, this is good enough.

Flushing the output buffer to a file

For efficiency, some compilers and operating systems may use a buffer as an intermediate storage of output before dumping it into a file. The motivation for using buffers is that writing to a file too often may keep the disk busier than necessary. By using a buffer, the program writes to disk only when the data exceeds the buffer size. For a more responsive behavior, you may want to explicitly write to disk whatever is currently stored in the buffer, using the flush statement.

Furthermore, the program will write to a file only after the user presses Enter to make a new line in the note. This is the case because the read statement won’t execute until the user enters the whole line. Thus, if you exit the program by pressing Ctrl+C halfway through the note, the line in progress will be lost.

Let’s now see how we can add more nuanced functionality to the quick-note app. First, we’ll allow our app to write to existing files by appending notes to them. Second, we’ll add a prompt to ask the user what action to take if the file for writing notes to already exists. In doing so, we’ll cover some optional parameters to the open statement. We’ll also learn about the inquire statement and how to use it to get information about a file without opening it.

Writing to a file

Leave a Reply

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

Scroll to top