Fortran Read Last Line From File
Fortran allows you to read data from, and write data into files. In the last chapter, you have seen how to read data from, and write data to the terminal. In this chapter you will study file input and output functionalities provided by Fortran. You can read and write to one or more files.
I am a Fortran novice. I would like to be able to read a text file and save its contents in individual variables. I found a very helpful Fortran tutorial (http://www.math.hawaii.edu/~hile/fortran/fort7.htm#read), and I am trying to follow one of the examples listed there. Specifically, I made a text file called data.txt with the following text:
I have saved this text file in my current directory. Then, I have created a file test.f90 (also saving it in my current directory) containing the following code:
I am using the GNU Fortran compiler, which I think includes the features at least up to and including Fortran95. The above code appears to compile okay, at least with the default settings). But when I run the resulting executable, I get this error message:
Line 10 is the line READ(7,*) m, n, first. Can you please help me see what I am doing wrong in the above code?
3 Answers
I can reproduce both your exact error message and the correct output. I'm using gfortran on Windows, and Notepad to create the data file.
If you terminate the second data line with an end-of-line character (by hitting the Enter key), the program will show the correct output; if you don't terminate it, it will display the error during execution.
Basically, the runtime tries to read a line, but encounters an end-of-file character before it reaches the end of the line.
When I your sample program, with your sample data, it worked! Congratulations! Output was:
To guess a possible reason that it isn't working for you, sometimes Fortran executables can be sensitive to line endings, demanding the correct line-terminator for the OS, including on the last line of a data file. Conversely many editors will silently convert line endings. I commonly run into this problem with files written by Microsoft programs.
For some compilers it is important to add a new line after the last line with the data. For example gfortran is a compiler which needs that and it is quite logical. The Sun (Oracle) compiler doesn't need that.
Not the answer you're looking for? Browse other questions tagged textfile-iofortran or ask your own question.
Sed Remove Last Line From File
Almost all FORTRAN 77 programs read data from external sources such as files or the user's terminal, perform calculations on that data, and then write the results to other files or the terminal. FORTRAN 77 provides a powerful and flexible set of features for reading and writing data which are independent of the underlying operating system.
Unit Numbers
Every input or output device is identified by a small, positive integer known as the unit number. These unit numbers are used in READ
and WRITE
statements to indicates the source or destination for the operation. Two of these numbers are always pre-defined at the start of every FORTRAN 77 program: unit 5 corresponds to standard input, which is often the user's terminal, and unit 6 corresponds to standard output, which is also often the terminal but may be another device, such as a printer.
Example
This example reads a single integer value from standard input and writes it to standard output:
Unit numbers must be used when reading from or writing to external files. However, when using the standard pre-connected I/O devices, the unit number may be replaced by an asterisk *
.
READ and WRITE Statements
The READ
statement reads information from one or more records in a file or standard pre-connected input device (like the terminal) into a data-transfer-list of variables, array elements, etc. Its general form is
Correspondingly, the WRITE
statement prints information to one or more records in a file or standard pre-connected output device (like the terminal) from a data-transfer-list of variables, array elements, expressions, etc. Its general form is
The control-list is a set of keyword/value pairs which define the characteristics of the I/O. The unit number must always be given. The following table lists the standard specifiers in FORTRAN 77.
Keyword | Description | Permitted Values |
---|---|---|
UNIT | The unit number associates the READ or WRITE statement with the input or output device. The unit number is traditionally listed first and if it is, the UNIT= part of the keyword/value pair may be omitted. | Any small positive integer expression when referring to an external file or an asterisk * when referring to the standard pre-connected I/O device. |
FMT | The format specifies how the data in the data-transfer-list is to be arranged. The format value is traditionally listed second after the unit number. If the unit number is listed first and UNIT= is omitted, then the FMT= part of the keyword value pair may also be omitted provided it is listed second. | The label of a statement within the same program unit, a character expression or array containing the complete format specification, or an asterisk * for list-directed formatting. |
END | If a READ statement attempts to input a record beyond the end of the file, an end-of-file condition will be triggered and the program will jump to the statement with the specified label. | The label of a statement within the same program unit. |
ERR | If an error occurs during input or output, the program will jump to the statement with the specified label. | The label of a statement within the same program unit. |
IOSTAT | After the READ or WRITE statement has been executed, the specified variable will contain a status value. This will be zero if the record was input or output successfully. Otherwise, it will be a non-zero value whose meaning is dependent on the operating system. | The name of an integer variable or array element with the same program unit. |
REC | A record number identifier must be used only with direct-access files. | An integer expression greater than zero. |
Example
The READ
statement is reading in three values from a file associated with the unit number 7 into array elements COUNT(I)
, A(I)
and NAME(I)
where I
is the loop-control-variable of the enclosing DO
loop.If an error occurs during the READ
statement, control will be transferred to the statement labelled 900 (which is a STOP
Marvel avengers alliance hack facebook new version. statement in this case.) If the end of the file is reached before 300 valuesare read in, then control will be transferred to the statement labelled 20 which writes a message to the standard output device and the program continues from there.
Formatting
When no specific formatting is specified by the programmer, the computer uses a system-dependent system called list-directed formatting.For output, the formatting depends on the data type of the item and varies from system to system. In general, however, the following rules apply:
- each
WRITE
statement starts a new record or line; - arithmetic data types are given to the number of digits appropriate for the internal precision;
- the system will choose decimal or exponential form for floating point numbers, according to the magnitude of the value;
COMPLEX
data types are output as(
real,
imaginary)
;LOGICAL
data types are output as a single T or F;CHARACTER
data types are output as a string without enclosing apostrophes;- except for
CHARACTER
values, all items are followed by a blank or comma to separate it from the next value.
As for input, list-directed formatting allows free-format entry for numerical data. The following rules are generally applicable:
- each
READ
statement starts with a new record or line, and reads as many records as is necessary to complete its (the file must already exist),'NEW'
(the file must not exist),'UNKNOWN'
(the file may or may not exist), or'SCRATCH'
(the file is a scratch file). No other values are allowed.
The default is'UNKNOWN'
.ERR
If an error occurs whilst opening the file, the program will jump to the statement with the specified label.The label of a statement within the same program unit.IOSTAT
After theOPEN
statement has been executed, the specified variable will contain a status value. This will be zero if the file was opened successfully. Otherwise, it will be a non-zero value whose meaningis dependent on the operating system.The name of an integer variable or array element within the same program unit.FORM
Whether the file is to be used for formatted (plain text) or unformatted (binary) I/O.'FORMATTED'
or'UNFORMATTED'
. No other values are allowed.
The default is'FORMATTED'
.ACCESS
Whether the file is to be used for sequential or random I/O.'SEQUENTIAL'
or'DIRECT'
. No other values are allowed.
The default is'SEQUENTIAL'
.RECL
The record length for direct access files.An integer which defines the record length.BLANK
Controls how blanks are to be interpreted in formatted numeric fields.'NULL'
(blanks are to be ignored) or'ZERO'
(blanks are to be treated as if they were zeros). No other values are allowed.
The default is'NULL'
.Example
Unit number 13 will be associated with the file whose name is input by the user. If there is an error opening the file (perhaps it doesn't exist or there is some other problem), then control will transfer to the statement labelled 100, prompting the user to input a different name. If the file is opened successfully, blanks will treated as if they were zeros. Note that if the user enters the (system-dependent) end-of-file character during the
READ
statement, control will transfer to a statement labelled 999.Scratch Files
FORTRAN 77 provides an easy way to open a temporary file to act as scratch storage for a program. Consider the following example:
Example
Unit number 8 will be associated with a temporary unnamed file which can be used for I/O in exactly the same way as any other file. However, after the file is closed, or if the program terminates without explicitly closing the file, the scratch file will be deleted automatically by the FORTRAN 77 I/O subsystem.
Note that no name is specified for the file in the
OPEN
statement. Indeed, it is forbidden to specify a file name for a scratch file.Closing a File
When a file is no longer required by the program, it should be closed. This breaks the association between the file and its unit number. The general form of this statement is
The control-list is a set of keyword/value pairs which define the how the file is to be closed. The unit number must always be given. The following table lists the standard specifiers in FORTRAN 77.
Keyword Description Permitted Values UNIT
The unit number is associated with the file from the time it is opened until it is closed. The unit number is traditionally listed first and if it is, the UNIT=
part of the keyword/value pair may be omitted.Any small positive integer expression. STATUS
This is used to specify whether the file should be kept or deleted after being closed. 'KEEP'
(the file should be kept after closing) or'DELETE'
(the file should be deleted). No other values are allowed.
The default is'KEEP'
, except for scratch files, which are always deleted after being closed.ERR
If an error occurs whilst closing the file, the program will jump to the statement with the specified label. The label of a statement within the same program unit. IOSTAT
After the CLOSE statement has been executed, the specified variable will contain a status value. This will be zero if the file was closed successfully. Otherwise, it will be a non-zero value whose meaning is dependent on the operating system. The name of an integer variable or array element within the same program unit. Example
The file associated with unit number 27 is deleted after being closed. The file associated with unit number 39 is kept after being closed unless it was opened as a scratch file in which case it is automatically deleted.
INQUIRE Statement
The
INQUIRE
statement is useful when you wish to learn more about a file, such as whether it exists or if it is already connected. Thisstatement takes on two slightly different forms. If you wish to determine whether a unit number is already in use and the characteristics of the file associated with it, then you use the inquire by unit form for the statement:If no file is connected to the specified unit number, then most of the arguments in the inquire-list will be undefined or return
'UNKNOWN'
as their values.The inquire by file form of the statement can be used to find out whether or not a named file exists.
You may inquire by unit or inquire by file but not both in the same
INQUIRE
command.The inquire-list is a set of keyword/value pairs which return values to the named variables or array elements. (The only exception is
ERR=
label where label is the label of a statement within the same program unit.) The following table lists the standard specifiers in FORTRAN 77.Keyword Description Permitted Values UNIT
The unit number is associated with the file from the time it is opened until it is closed. The UNIT=
part of the keyword/value pair may be omitted in the inquire by unit statement.
EitherUNIT
orFILE
must be used but not both.Any small positive integer expression. FILE
The name of the file which is to be associated with this unit. Trailing blanks in the file name are ignored and the file need not be connected to a unit in the program.
EitherUNIT
orFILE
must be used but not both.The name of a character variable or array element within the same program unit. ERR
If an error occurs whilst executing the INQUIRE
command, the program will jump to the statement with the specified label. This does not infer that there is an error with the unit number or file.The label of a statement within the same program unit. IOSTAT
After the INQUIRE
statement has been executed, the specified variable will contain a status value. This will be zero if the command was executed successfully. Otherwise, it will be a non-zero value whose meaningis dependent on the operating system. This does not infer that there is an error with the unit number or file.The name of an integer variable or array element within the same program unit. EXIST
The variable is set to .TRUE.
if the specified unit file exists and.FALSE.
otherwise.The name of a logical variable or array element within the same program unit. OPENED
The variable is set to .TRUE.
if the specified unit file is connected to a file unit in the program and.FALSE.
otherwise.The name of a logical variable or array element within the same program unit. NAMED
The variable is set to .TRUE.
if the file has a nameand.FALSE.
otherwise.The name of a logical variable or array element within the same program unit. NAME
The variable returns the file name if the file has a name; otherwise it is undefined. If a name is returned, it is suitable for use in the OPEN
statement.The name of a character variable or array element within the same program unit. NUMBER
The variable returns the unit number of the file which is connected. Ifno file is connected, the variable is undefined. This specifier cannot be used in the inquire by unit statement. The name of an integer variable or array element within the same program unit. ACCESS
The variable returns 'SEQUENTIAL'
if the connection is for sequential I/O or'DIRECT'
if the connection is for direct I/O. The value is undefined if there is no connection.The name of a character variable or array element within the same program unit. DIRECT
The variable returns 'YES'
if the file can be connected for direct I/O,'NO'
if it can't, and'UNKNOWN'
if the system can't tell.The name of a character variable or array element within the same program unit. SEQUENTIAL
The variable returns 'YES'
if the file can be connected for sequential I/O,'NO'
if it can't, and'UNKNOWN'
if the system can't tell.The name of a character variable or array element within the same program unit. FORM
The variable returns 'FORMATTED'
if the connection is for formatted I/O or'UNFORMATTED'
if the connection is for unformatted I/O. The value is undefined if there is no connection.The name of a character variable or array element within the same program unit. FORMATTED
The variable returns 'YES'
if the file can be connected for formatted I/O,'NO'
if it can't, and'UNKNOWN'
if the system can't tell.The name of a character variable or array element within the same program unit. UNFORMATTED
The variable returns 'YES'
if the file can be connected for unformatted I/O,'NO'
if it can't, and'UNKNOWN'
if the system can't tell.The name of a character variable or array element within the same program unit. RECL
The variable returns the record length if the file is connected for direct-access and is undefined otherwise. The record length is the number of characters in a formatted file but the units are system-dependent for unformatted files. The name of an integer variable or array element within the same program unit. NEXTREC
The variable returns the value n + 1 where n is the record number of the last record transferred to/from a direct-access file. If no records have been transferred, then the value 1 is returned. The value is undefined otherwise. The name of an integer variable or array element within the same program unit. BLANK
The variable returns 'NULL'
if null blank control is in effect for the file connected for formatted I/O or'ZERO'
if blanks are being converted to zeros. The value is undefined if there is no connection.The name of a character variable or array element within the same program unit. Example
Suppose we need to open a named file within a subroutine, but do not knowwhich unit numbers are available. We can use
INQUIRE
to findthe smallest unit number that is not currently in use. This simple functionsearches all unit numbers within a specified range, and returns the smallestnumber which does not already have an open file associated with it. If allunit numbers in the range are in use, the function returns the special value-1.Unformatted I/O
When reading or writing very large data sets, it is often more efficient to store the data in the host machine's native binary format rather than in human-readable format. FORTRAN 77 provides unformatted I/O for this purpose. Unformatted files are generally more compact and can be read and written much more quickly, because there is no need for the computer to convert between human-readable text and its native binary format.
However, unformatted files cannot be opened with a text editor. They can only be read by a FORTRAN 77 program.
Example
Suppose we run the following short program:
On an Intel-based Linux machine, this produces a file named xample.out which is 24 bytes long. When we examine its contents using the hd (hexadecimal dump) utility, we see this:
I am trying to keep it under 75.00 if possible I have spent about 325.00 on the three I have had. I have gone thru 3 Microsoft models so far one had the space bar stop working, the next was the corded transceiver would come and go and now this. Buy would prefer to just buy a replacement tranceiver if there is such a thing that will work this this keyboard / mouse??? Any suggestions? Microsoft 2.4ghz transceiver v7.0 driver. It is for home use mostly.
The first four bytes are a record length, generated automatically by the FORTRAN 77 I/O subsystem. It is in little-endian byte order, so the value in decimal is 16. Then follow the actual data which the program wrote: the two 32-bit integers in little-endian byte order, and the IEEE754 double-precision (64-bit) number. Finally, the record length is written again by the FORTRAN 77 I/O subsystem as a safeguard.
Sequential I/O
Most programs use sequential I/O. They open a data file, and read its contents from start to finish, processing the values as they are read, and writing results to an output file.
REWIND Statement
It is possible to re-read a sequential input file from the first record by using the
REWIND
command. The name is a reminder that FORTRAN originates from an era when magnetic tapes were the most common mass-storage medium. TheREWIND
command once did exactly what its name implies: it caused a magnetic tape to be rewound to the start, so that the data on it could be re-read.The general form of this statement is
The control-list must contain the
UNIT
specifier and may contain theERR
andIOSTAT
specifiers, which have exactly the same syntax and meaning as their counterparts in theOPEN
andCLOSE
statements. As always, if the unit number is listed first in the control-list, theUNIT=
part of the keyword/value pair may be omitted.BACKSPACE Statement
If the program needs to re-read only the most recently read (or written) record, then the
BACKSPACE
statement can be used. The general form of this statement isThe control list may contain the same specifiers as the
REWIND
statement.Direct I/O
Some programs may need to access records in a data file in a non-sequential manner. Consider, for example, a data file which contains customer information, with one record per customer. It would be inefficient to read the entire file in order to obtain the data on a single customer. Instead, the program should be able to skip all of the intervening records, and readonly the record for that customer. FORTRAN 77 provides direct-access I/O for this purpose.
In order to make direct-access I/O efficient, FORTRAN 77 mandates that all records in a direct-access file must be exactly the same length. This allows the FORTRAN 77 I/O subsystem to determine the offset of the desired record in the file by performing a simple arithmetic calculation. It is the programmer's responsibility to specify the correct record length when opening the file.
Direct-access I/O is normally carried out on unformatted files, although it can also be used with formatted files, if sufficient caution is used.
Example
Suppose we run the following short program:
On an Intel-based Linux machine, this produces a file named xample.out which is 16 bytes long. When we examine its contents using the hd (hexadecimal dump) utility, we see this:
The file contains a single 16-byte record comprising the two 32-bit integers and the 64-bit floating point number.
FORTRAN 77 allows us to write to any record in a direct-access file. We do not have to write the records sequentially. We can open a new file and write record number 3 without having to write records 1 and 2.
Example
If we modify the previous program slightly, changing the
WRITE
statement toand then re-compile and re-run the program, the output file is now 48 bytes long, and its contents, displayed by the hd utility, look like this:
Notice that there are three 16-byte records in the file, but the first two are filled with nulls. Only record number 3 contains valid data.
Internal Files
The files discussed above are all external files. FORTRAN 77 also allows computer memory to be used as if it was an external file. This internal file exists only whilst the program is executing and behaves like a formatted sequential file.
An internal file is a
CHARACTER
object such as a constant, variable, substring, array or array element, and is most often used for converting betweenCHARACTER
and other data types. It is accessed only withREAD
andWRITE
statements with explicit format specifications. However, instead of a number, the unit in theREAD
orWRITE
statement must be an object of typeCHARACTER
.Example
Consider the following program fragment. We wish to use an internal file to assign a value to the
CHARACTER
variableTITLE
.The second
WRITE
statement uses theFORMAT
statement labelled100
to write text and integers to theCHARACTER
variableTITLE
. IfSTIME
is initialised to15.6
, theTITLE
contains thevaluewhere
␣
is a blank.Example
Consider the following program fragment where we have information stored in a
CHARACTER
variable but wish to convert it to another type (in this caseINTEGER
) by means of an internal file.The
CHARACTER
variable contains the value1␣2␣3␣4␣5␣
where␣
is a blank. TheREAD
statement uses an internal file to convert this value usingthe format specification(2I5)
into two variables of typeINTEGER
. The first 5 places are placed in the variableI
and the second 5 places are placed inJ
. As a result,I
contains the value123
andJ
contains45
. (The blanks are ignored.)However, if we change the
READ
statement toI
takes the value10203
andJ
becomes04050
. This is because the descriptorBZ
forces blanks to be treated as zeros.The statements
BACKSPACE
andREWIND
may be used with internal files but no other I/O commands are permitted.Table of ContentsIndexFormat Descriptors
Copyright © 1995-2014 by David Harper and L.M. Stockman
All Rights Reserved
Designed and maintained by Obliquity
https://www.obliquity.com/computer/fortran/io.html