Fortran Read Last Line From File

  

Next: Invoking G++, Previous: Option Summary, Up: Invoking GCC [Contents][Index]

Each Fortran read statement, by default, reads a list of values and then advances to the beginning of the next line. Think of read as moving a cursor through the input file as it works. So your statement. Read(100,.) test does what you expect when the numbers in the input file are on separate lines. An internal file to Fortran is simply a CHARACTER.n variable. Just give the name of the variable (it may be a substring if you wish) instead of the unit number in a Fortran READ or WRITE statement. Note that you must still write to a string and send the string to qprint or xvmessage. Read command-line options from file. The options read are inserted in place of the original @file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed. Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option. How to skip over data in FORTRAN. How to skip entire lines of data. One way to do this is to put in a READ statement for each line that you want to 'skip'. Each time a READ statement is encountered, it reads in the data and then moves the 'pointer' in the file down to the next line. For a variable or substring, there is only a single record in the file but for an array; each array element is a record. Sequential Formatted I/O. On internal files, the FORTRAN Standard includes only sequential formatted I/O. (I/O is not a precise term to use here, but internal files are dealt with using READ and WRITE statements.) Internal.

3.2 Options Controlling the Kind of Output

Compilation can involve up to four stages: preprocessing, compilationproper, assembly and linking, always in that order. Mac and devin go to high school movie torrent. GCC is capable ofpreprocessing and compiling several files either into severalassembler input files, or into one assembler input file; then eachassembler input file produces an object file, and linking combines allthe object files (those newly compiled, and those specified as input)into an executable file.

For any given input file, the file name suffix determines what kind ofcompilation is done:

file.c

C source code that must be preprocessed.

file.i

C source code that should not be preprocessed.

file.ii

C++ source code that should not be preprocessed.

file.m

Objective-C source code. Note that you must link with the libobjclibrary to make an Objective-C program work.

file.mi

Objective-C source code that should not be preprocessed.

file.mm
file.M

Objective-C++ source code. Note that you must link with the libobjclibrary to make an Objective-C++ program work. Note that ‘.M’ refersto a literal capital M.

file.mii

Objective-C++ source code that should not be preprocessed.

file.h

C, C++, Objective-C or Objective-C++ header file to be turned into aprecompiled header (default), or C, C++ header file to be turned into anAda spec (via the -fdump-ada-spec switch).

file.cc
file.cp
file.cxx
file.cpp
file.CPP
file.c++
file.C

C++ source code that must be preprocessed. Note that in ‘.cxx’,the last two letters must both be literally ‘x’. Likewise,‘.C’ refers to a literal capital C.

file.mm
file.M

Objective-C++ source code that must be preprocessed.

file.mii

Objective-C++ source code that should not be preprocessed.

file.hh
file.H
file.hp
file.hxx
File
file.hpp

Fortran Read Specific Line From File

file.HPP
file.h++
file.tcc

C++ header file to be turned into a precompiled header or Ada spec.

file.f
Line
file.for
file.ftn

Fixed form Fortran source code that should not be preprocessed.

file.F
file.FOR
file.fpp
file.FPP
file.FTN

Fixed form Fortran source code that must be preprocessed (with the traditionalpreprocessor).

file.f90
file.f95
file.f03
file.f08

Free form Fortran source code that should not be preprocessed.

file.F90
file.F95
file.F03
file.F08

Free form Fortran source code that must be preprocessed (with thetraditional preprocessor).

file.go

Go source code.

file.brig

BRIG files (binary representation of HSAIL).

file.d

D source code.

file.di

D interface file.

file.dd

D documentation code (Ddoc).

file.ads

Ada source code file that contains a library unit declaration (adeclaration of a package, subprogram, or generic, or a genericinstantiation), or a library unit renaming declaration (a package,generic, or subprogram renaming declaration). Such files are alsocalled specs.

file.adb

Ada source code file containing a library unit body (a subprogram orpackage body). Such files are also called bodies.

file.s

Assembler code.

file.S
file.sx

Assembler code that must be preprocessed.

other

An object file to be fed straight into linking.Any file name with no recognized suffix is treated this way.

You can specify the input language explicitly with the -x option:

-x language

Specify explicitly the language for the following input files(rather than letting the compiler choose a default based on the filename suffix). This option applies to all following input files untilthe next -x option. Possible values for language are:

-x none

Turn off any specification of a language, so that subsequent files arehandled according to their file name suffixes (as they are if -xhas not been used at all).

If you only want some of the stages of compilation, you can use-x (or filename suffixes) to tell gcc where to start, andone of the options -c, -S, or -E to say wheregcc is to stop. Note that some combinations (for example,‘-x cpp-output -E’) instruct gcc to do nothing at all.

-c

Compile or assemble the source files, but do not link. The linkingstage simply is not done. The ultimate output is in the form of anobject file for each source file.

By default, the object file name for a source file is made by replacingthe suffix ‘.c’, ‘.i’, ‘.s’, etc., with ‘.o’.

Unrecognized input files, not requiring compilation or assembly, areignored.

-S

Stop after the stage of compilation proper; do not assemble. The outputis in the form of an assembler code file for each non-assembler inputfile specified.

By default, the assembler file name for a source file is made byreplacing the suffix ‘.c’, ‘.i’, etc., with ‘.s’.

Input files that don’t require compilation are ignored.

-E

Stop after the preprocessing stage; do not run the compiler proper. Theoutput is in the form of preprocessed source code, which is sent to thestandard output.

Input files that don’t require preprocessing are ignored.

-o file

Place output in file file. This applies to whateversort of output is being produced, whether it be an executable file,an object file, an assembler file or preprocessed C code.

If -o is not specified, the default is to put an executablefile in a.out, the object file forsource.suffix in source.o, itsassembler file in source.s, a precompiled header file insource.suffix.gch, and all preprocessed C source onstandard output.

-v

Print (on standard error output) the commands executed to run the stagesof compilation. Also print the version number of the compiler driverprogram and of the preprocessor and the compiler proper.

-###

Like -v except the commands are not executed and argumentsare quoted unless they contain only alphanumeric characters or ./-_.This is useful for shell scripts to capture the driver-generated command lines.

--help

Print (on the standard output) a description of the command-line optionsunderstood by gcc. If the -v option is also specifiedthen --help is also passed on to the various processesinvoked by gcc, so that they can display the command-line optionsthey accept. If the -Wextra option has also been specified(prior to the --help option), then command-line options thathave no documentation associated with them are also displayed.

--target-help

Print (on the standard output) a description of target-specific command-lineoptions for each tool. For some targets extra target-specificinformation may also be printed.

--help={class [^]qualifier}[,…]

Print (on the standard output) a description of the command-lineoptions understood by the compiler that fit into all specified classesand qualifiers. These are the supported classes:

optimizers

Display all of the optimization options supported by thecompiler.

warnings

Display all of the options controlling warning messagesproduced by the compiler.

target

Display target-specific options. Unlike the--target-help option however, target-specific options of thelinker and assembler are not displayed. This is because thosetools do not currently support the extended --help= syntax.

params

Display the values recognized by the --paramoption.

language

Display the options supported for language, wherelanguage is the name of one of the languages supported in thisversion of GCC. If an option is supported by all languages, one needsto select ‘common’ class.

common

Display the options that are common to all languages.

These are the supported qualifiers:

undocumented

Display only those options that are undocumented.

joined

Display options taking an argument that appears after an equalsign in the same continuous piece of text, such as:‘--help=target’.

separate

Display options taking an argument that appears as a separate wordfollowing the original option, such as: ‘-o output-file’.

Thus for example to display all the undocumented target-specificswitches supported by the compiler, use:

The sense of a qualifier can be inverted by prefixing it with the‘^’ character, so for example to display all binary warningoptions (i.e., ones that are either on or off and that do not take anargument) that have a description, use:

The argument to --help= should not consist solely of invertedqualifiers.

Combining several classes is possible, although this usuallyrestricts the output so much that there is nothing to display. Onecase where it does work, however, is when one of the classes istarget. For example, to display all the target-specificoptimization options, use:

The --help= option can be repeated on the command line. Eachsuccessive use displays its requested class of options, skippingthose that have already been displayed. If --help is alsospecified anywhere on the command line then this takes precedenceover any --help= option.

If the -Q option appears on the command line before the--help= option, then the descriptive text displayed by--help= is changed. Instead of describing the displayedoptions, an indication is given as to whether the option is enabled,disabled or set to a specific value (assuming that the compilerknows this at the point where the --help= option is used).

From

Here is a truncated example from the ARM port of gcc:

The output is sensitive to the effects of previous command-lineoptions, so for example it is possible to find out which optimizationsare enabled at -O2 by using:

Alternatively you can discover which binary optimizations are enabledby -O3 by using:

--version

Display the version number and copyrights of the invoked GCC.

-pass-exit-codes

Normally the gcc program exits with the code of 1 if anyphase of the compiler returns a non-success return code. If you specify-pass-exit-codes, the gcc program instead returns withthe numerically highest error produced by any phase returning an errorindication. The C, C++, and Fortran front ends return 4 if an internalcompiler error is encountered.

-pipe

Use pipes rather than temporary files for communication between thevarious stages of compilation. This fails to work on some systems wherethe assembler is unable to read from a pipe; but the GNU assembler hasno trouble.

-specs=file

Process file after the compiler reads in the standard specsfile, in order to override the defaults which the gcc driverprogram uses when determining what switches to pass to cc1,cc1plus, as, ld, etc. More than one-specs=file can be specified on the command line, and theyare processed in order, from left to right. See Spec Files, forinformation about the format of the file.

Read
-wrapper

Invoke all subcommands under a wrapper program. The name of thewrapper program and its parameters are passed as a comma separatedlist.

This invokes all subprograms of gcc under‘gdb --args’, thus the invocation of cc1 is‘gdb --args cc1 …’.

-ffile-prefix-map=old=new

When compiling files residing in directory old, recordany references to them in the result of the compilation as if thefiles resided in directory new instead. Specifying thisoption is equivalent to specifying all the individual-f*-prefix-map options. This can be used to make reproduciblebuilds that are location independent. See also-fmacro-prefix-map and -fdebug-prefix-map.

-fplugin=name.so

Load the plugin code in file name.so, assumed to be ashared object to be dlopen’d by the compiler. The base name ofthe shared object file is used to identify the plugin for thepurposes of argument parsing (See-fplugin-arg-name-key=value below).Each plugin should define the callback functions specified in thePlugins API.

-fplugin-arg-name-key=value

Define an argument called key with a value of valuefor the plugin called name.

-fdump-ada-spec[-slim]

For C and C++ source and include files, generate corresponding Ada specs.See Generating Ada Bindings for C and C++ headers in GNAT User’s Guide, which provides detailed documentation on this feature.

-fada-spec-parent=unit

In conjunction with -fdump-ada-spec[-slim] above, generateAda specs as child units of parent unit.

-fdump-go-spec=file

For input files in any language, generate corresponding Godeclarations in file. This generates Go const,type, var, and func declarations which may be auseful way to start writing a Go interface to code written in someother language.

@file

Read command-line options from file. The options read areinserted in place of the original @file option. If filedoes not exist, or cannot be read, then the option will be treatedliterally, and not removed.

Options in file are separated by whitespace. A whitespacecharacter may be included in an option by surrounding the entireoption in either single or double quotes. Any character (including abackslash) may be included by prefixing the character to be includedwith a backslash. The file may itself contain [email protected]file options; any such options will be processed recursively.

Next: Invoking G++, Previous: Option Summary, Up: Invoking GCC [Contents][Index]

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.

Fortran Read Last Line From File

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 *.

Fortran Read Data From File

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.

Fortran Write To File

KeywordDescriptionPermitted Values
UNITThe 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.
FMTThe 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.
ENDIf 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.
ERRIf 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.
IOSTATAfter 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.
RECA 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 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.
Fortran read last line from file command

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'.ERRIf 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.IOSTATAfter the OPEN 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.FORMWhether 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'.ACCESSWhether the file is to be used for sequential or random I/O.'SEQUENTIAL' or 'DIRECT'. No other values are allowed.
    The default is 'SEQUENTIAL'.RECLThe record length for direct access files.An integer which defines the record length.BLANKControls 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.

    KeywordDescriptionPermitted Values
    UNITThe 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.
    STATUSThis 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.
    ERRIf 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.
    IOSTATAfter 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 isERR=label where label is the label of a statement within the same program unit.) The following table lists the standard specifiers in FORTRAN 77.

    KeywordDescriptionPermitted Values
    UNITThe 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.
    Either UNIT or FILE must be used but not both.
    Any small positive integer expression.
    FILEThe 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.
    Either UNIT or FILE must be used but not both.
    The name of a character variable or array element within the same program unit.
    ERRIf 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.
    IOSTATAfter 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.
    EXISTThe 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.
    OPENEDThe 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.
    NAMEDThe 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.
    NAMEThe 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.
    NUMBERThe 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.
    ACCESSThe 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.
    DIRECTThe 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.
    SEQUENTIALThe 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.
    FORMThe 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.
    FORMATTEDThe 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.
    UNFORMATTEDThe 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.
    RECLThe 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.
    NEXTRECThe 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.
    BLANKThe 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:

    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. The REWIND 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 the ERR and IOSTAT specifiers, which have exactly the same syntax and meaning as their counterparts in the OPEN and CLOSE statements. As always, if the unit number is listed first in the control-list, the UNIT= 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 is

    The 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 to

    and 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 between CHARACTER and other data types. It is accessed only with READ and WRITE statements with explicit format specifications. However, instead of a number, the unit in the READ or WRITE statement must be an object of type CHARACTER.

    Example

    Consider the following program fragment. We wish to use an internal file to assign a value to the CHARACTER variable TITLE.

    The second WRITE statement uses the FORMAT statement labelled 100 to write text and integers to the CHARACTER variable TITLE. If STIME is initialised to 15.6, the TITLE contains thevalue

    where 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 case INTEGER) by means of an internal file.

    The CHARACTER variable contains the value 12345 where is a blank. The READ statement uses an internal file to convert this value usingthe format specification (2I5) into two variables of type INTEGER. The first 5 places are placed in the variable I and the second 5 places are placed in J. As a result, I contains the value 123 and J contains 45. (The blanks are ignored.)

    However, if we change the READ statement to

    I takes the value 10203 and J becomes04050. This is because the descriptor BZ forces blanks to be treated as zeros.

    The statements BACKSPACE and REWIND may be used with internal files but no other I/O commands are permitted.

    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