Reading Variables From a File in Fortran

C H A P T Due east R 2

Fortran Input/Output

This chapter discusses the input/output features provided by the Sunday Studio Fortran 95 compiler.

2.1 Accessing Files From Within Fortran Programs

Data is transferred betwixt the plan and devices or files through a Fortran logical unit. Logical units are identified in an I/O statement past a logical unit number, a nonnegative integer from 0 to the maximum iv-byte integer value (2,147,483,647).

The graphic symbol * can appear every bit a logical unit identifier. The asterisk stands for standard input file when it appears in a READ statement; it stands for standard output file when information technology appears in a WRITE or PRINT argument.

A Fortran logical unit tin be associated with a specific, named file through the OPEN statement. Besides, certain preconnected units are automatically associated with specific files at the start of program execution.

2.i.1 Accessing Named Files

The Open statement'south FILE= specifier establishes the association of a logical unit to a named, physical file at runtime. This file can be pre-existing or created by the program.

The FILE= specifier on an OPEN statement may specify a unproblematic file proper noun (FILE='myfile.out') or a file name preceded by an absolute or relative directory path (FILE='../Amber/Qproj/myfile.out'). Also, the specifier may be a character constant, variable, or graphic symbol expression.

Library routines can exist used to bring command-line arguments and environment variables into the program as character variables for use as file names in OPEN statements.

The post-obit example (GetFilNam.f) shows ane fashion to construct an accented path file name from a typed-in name. The programme uses the library routines GETENV, LNBLNK, and GETCWD to return the value of the $Home environment variable, find the concluding not-bare in the string, and make up one's mind the electric current working directory:

            Grapheme F*128, FN*128, FULLNAME*128          
            PRINT*, 'ENTER FILE NAME:'          
            READ *, F          
            FN = FULLNAME( F )          
            PRINT *, 'PATH IS: ',FN          
            END          
          
            Character*128 FUNCTION FULLNAME( NAME )          
            CHARACTER Name*(*), PREFIX*128          
C          This assumes C shell.          
C           Leave absolute path names unchanged.          
C           If name starts with '~/', replace tilde with home          
C           directory; otherwise prefix relative path proper noun with          
C           path to current directory.          
            IF ( Proper name(1:i) .EQ. '/' ) THEN          
            FULLNAME = Name          
            ELSE IF ( NAME(1:2) .EQ. '~/' ) So          
            Phone call GETENV( 'HOME', PREFIX )          
            FULLNAME = PREFIX(:LNBLNK(PREFIX)) //          
            1                     Name(2:LNBLNK(NAME))          
            ELSE          
            Call GETCWD( PREFIX )          
            FULLNAME = PREFIX(:LNBLNK(PREFIX)) //          
            i                     '/' // NAME(:LNBLNK(Proper name))          
            ENDIF          
            Render          
            END          

Compiling and running GetFilNam.f results in:

demo%            pwd          
/dwelling/users/auser/subdir          
demo%              f95 -o getfil GetFilNam.f          
demo%            getfil          
            ENTER FILE NAME:          
            getfil          
            PATH IS: /home/users/auser/subdir/atest.f          
          
demo%          

These routines are further described in Section 2.1.iv, Passing File Names to Programs. Run across man page entries for getarg(3F), getcwd(3F), and getenv(3F) for details; these and other useful library routines are also described in the Fortran Library Reference.

2.1.2 Opening Files Without a Proper noun

The OPEN argument demand not specify a name; the runtime system supplies a file name co-ordinate to several conventions.

2.1.two.1 Opened every bit Scratch

Specifying Status='SCRATCH' in the OPEN statement opens a file with a name of the course tmp.F AAAxnnnnn, where nnnnn is replaced by the current procedure ID, AAA is a string of three characters, and ten is a alphabetic character; the AAA and x make the file proper name unique. This file is deleted upon termination of the program or execution of a CLOSE statement. When compiling in FORTRAN 77 compatibility mode (-f77), you tin specify STATUS='Go on' in the Close statement to preserve the scratch file. (This is a not-standard extension.)

ii.one.2.ii Already Open

If the file has already been opened by the program, y'all can use a subsequent Open up statement to change some of the file's characteristics; for instance, Blank and FORM. In this instance, y'all would specify only the file'south logical unit number and the parameters to change.

ii.i.ii.three Preconnected or Implicitly Named Units

Three unit numbers are automatically associated with specific standard I/O files at the start of program execution. These preconnected units are standard input, standard output, and standard error:

  • Standard input is logical unit 5
  • Standard output is logical unit six
  • Standard error is logical unit 0

Typically, standard input receives input from the workstation keyboard; standard output and standard error display output on the workstation screen.

In all other cases where a logical unit of measurement number but no FILE= name is specified on an OPEN statement, a file is opened with a name of the form fort. n, where due north is the logical unit number.

2.1.three Opening Files Without an Open up Statement

Use of the Open statement is optional in those cases where default conventions can be causeless. If the offset performance on a logical unit is an I/O argument other than Open up or INQUIRE, the file fort. n is referenced, where n is the logical unit number (except for 0, 5, and 6, which have special meaning).

These files demand not exist earlier program execution. If the get-go operation on the file is not an Open or INQUIRE statement, they are created.

Example: The WRITE in the following code creates the file fort.25 if it is the first input/output operation on that unit:

demo%            cat TestUnit.f          
            IU=25          
            WRITE( IU, '(I4)' ) IU          
            END          
demo%          

The preceding program opens the file fort.25 and writes a single formatted record onto that file:

demo%              f95 -o testunit TestUnit.f          
demo%            testunit          
demo%            cat fort.25          
            25          
demo%          

2.1.4 Passing File Names to Programs

The file organization does not have whatever automatic facility to associate a logical unit number in a Fortran program with a physical file.

However, at that place are several satisfactory ways to communicate file names to a Fortran program.

2.1.4.i Via Runtime Arguments and GETARG

The library routine getarg(3F) can be used to read the control-line arguments at runtime into a graphic symbol variable. The argument is interpreted as a file name and used in the OPEN statement FILE= specifier:

demo%            true cat testarg.f          
            Character outfile*40          
C  Get first arg as output file name for unit of measurement 51          
            Phone call getarg(1,outfile)          
            Open(51,FILE=outfile)          
            WRITE(51,*) 'Writing to file: ', outfile          
            END          
demo%            f95 -o tstarg testarg.f          
demo%            tstarg AnyFileName          
demo%            cat AnyFileName          
            Writing to file: AnyFileName          
demo%          

2.1.4.ii Via Environment Variables and GETENV

Similarly, the library routine getenv(3F) tin exist used to read the value of any environs variable at runtime into a graphic symbol variable that in plow is interpreted as a file name:

demo%            cat testenv.f          
            Grapheme outfile*forty          
C  Become $OUTFILE equally output file name for unit 51          
            Phone call getenv('OUTFILE',outfile)          
            Open up(51,FILE=outfile)          
            WRITE(51,*) 'Writing to file: ', outfile          
            END          
demo%            f95 -o tstenv testenv.f          
demo%            setenv OUTFILE EnvFileName          
demo%            tstenv          
demo%            cat EnvFileName          
            Writing to file: EnvFileName          
demo%          

When using getarg or getenv, care should exist taken regarding leading or trailing blanks. (Fortran 95 programs tin employ the intrinsic part TRIM, or the older FORTRAN 77 library routine LNBLNK()) Additional flexibility to accept relative path names can be programmed along the lines of the FULLNAME function in the case at the beginning of this affiliate.

ii.1.4.three Command-Line I/O Redirection and Piping

Another way to associate a concrete file with a programme'southward logical unit number is by redirecting or piping the preconnected standard I/O files. Redirection or piping occurs on the runtime execution control.

In this way, a plan that reads standard input (unit 5) and writes to standard output (unit vi) or standard error (unit 0) tin can, by redirection (using <, >, >>, >&, |, |&, ii>, 2>&1 on the command line), read or write to any other named file.

This is shown in the following tabular array:

TABLE two-one csh/sh/ksh Redirection and Pipe on the Control Line

Action

Using C Shell

Using Bourne or Korn Shell

Standard input --
read from mydata

myprog < mydata

myprog < mydata

Standard output --
write (overwrite) myoutput

myprog > myoutput

myprog > myoutput

Standard output -- write/append to myoutput

myprog >> myoutput

myprog >> myoutput

Redirect standard fault to a file

myprog >& errorfile

myprog two> errorfile

Pipe standard output to input of some other program

myprog1 | myprog2

myprog1 | myprog2

Pipe standard error and output to some other program

myprog1 |& myprog2

myprog1 2>&1 | myprog2

See the csh, ksh, and sh man pages for details on redirection and piping on the command line.

2.2 Direct I/O

Straight or random I/O allows yous to admission a file directly past tape number. Record numbers are assigned when a record is written. Dissimilar sequential I/O, direct I/O records can be read and written in whatsoever order. All the same, in a direct access file, all records must be the same stock-still length. Direct access files are declared with the Admission='DIRECT' specifier on the OPEN argument for the file.

A logical tape in a direct access file is a string of bytes of a length specified past the OPEN statement's RECL= specifier. READ and WRITE statements must not specify logical records larger than the defined record size. (Tape sizes are specified in bytes.) Shorter records are allowed. Unformatted, direct writes get out the unfilled part of the record undefined. Formatted, directly writes cause the unfilled tape to exist padded with blanks.

Direct access READ and WRITE statements accept an extra argument, REC= due north, to specify the record number to be read or written.

Instance: Straight access, unformatted:

            Open( two, FILE='data.db', Access='Direct', RECL=200,          
&             Form='UNFORMATTED', ERR=90 )          
            READ( 2, REC=13, ERR=30 ) Ten, Y          

This program opens a file for direct access, unformatted I/O, with a fixed record length of 200 bytes, then reads the thirteenth tape into X and Y.

Example: Direct access, formatted:

            Open( 2, FILE='inven.db', Access='DIRECT', RECL=200,          
&             FORM='FORMATTED', ERR=90 )          
            READ( 2, FMT='(I10,F10.3)', REC=13, ERR=30 ) X, Y          

This program opens a file for direct access, formatted I/O, with a fixed tape length of 200 bytes. It so reads the thirteenth record and converts it with the format (I10,F10.three).

For formatted files, the size of the record written is determined by the FORMAT statement. In the preceding instance, the FORMAT statement defines a record of 20 characters or bytes. More than ane record can be written by a single formatted write if the amount of information on the listing is larger than the record size specified in the FORMAT statement. In such a case, each subsequent record is given successive record numbers.

Example: Direct admission, formatted, multiple record write:

            OPEN( 21, ACCESS='DIRECT', RECL=200, FORM='FORMATTED')          
            WRITE(21,'(10F10.three)',REC=11) (10(J),J=1,100)          

The write to direct access unit 21 creates 10 records of 10 elements each (since the format specifies 10 elements per record) these records are numbered 11 through 20.

ii.three Binary I/O

Dominicus Studio Fortran 95 extends the OPEN argument to allow declaration of a "binary" I/O file.

Opening a file with Form='BINARY' has roughly the same effect as FORM='UNFORMATTED', except that no record lengths are embedded in the file. Without this information, at that place is no manner to tell where one record begins, or ends. Thus, it is impossible to BACKSPACE a FORM='BINARY' file, because there is no manner of telling where to backspace to. A READ on a 'BINARY' file volition read equally much data as needed to fill up the variables on the input list.

  • WRITE statement: Data is written to the file in binary, with as many bytes transferred as specified by the output list.
  • READ statement: Data is read into the variables on the input list, transferring as many bytes every bit required by the listing. Because there are no record marks on the file, in that location will be no "finish-of-record" error detection. The simply errors detected are "stop-of-file" or abnormal system errors.
  • Ask statement: INQUIRE on a file opened with Form="BINARY" returns:
    FORM="BINARY"
    Access="SEQUENTIAL"
    Direct="NO"
    FORMATTED="NO"
    UNFORMATTED="Yeah"
    RECL= AND NEXTREC=
    are undefined
  • BACKSPACE statement: Non allowed--returns an error.
  • ENDFILE statement: Truncates file at current position, as usual.
  • REWIND statement: Repositions file to get-go of data, as usual.

ii.4 Stream I/O

A new "stream" I/O scheme has been proposed every bit part of the Fortran 2000 typhoon standard, and is implemented in f95. Stream I/O admission treats a data file equally a continuous sequence of bytes, addressable by a positive integer starting from 1. Declare a stream I/O file with the Access='STREAM' specifier on the OPEN statement. File positioning to a byte address requires a POS= scalar_integer_expression specifier on a READ or WRITE statement. The INQUIRE argument accepts Admission='STREAM', a specifier STREAM= scalar_character_variable, and POS= scalar_integer_variable.

Stream I/O is very useful when interoperating with files created or read past C programs, as is shown in the following example:

            Fortran 95 program reads files created past C            fwrite()          
          
programme reader          
            integer:: a(1024), i, result          
            open(file="examination", unit=eight, admission="stream",form="unformatted")          
! read all of a          
            read(viii) a          
            practice i = 1,1024          
            if (a(i) .ne. i-one) print *,'error at ', i          
            enddo          
! read the file backward          
            do i = 1024,one,-1          
            read(viii, pos=(i-one)*iv+1) outcome          
            if (outcome .ne. i-1) print *,'fault at ', i          
            enddo          
            close(viii)          
terminate          
          
            C program writes to a file          
          
#include <stdio.h>          
int binary_data[1024];          
          
/* Create a file with 1024 32-bit integers */          
int          
main(void)          
{          
            int i;          
            FILE *fp;          
          
            for (i = 0; i < 1024; ++i)          
            binary_data[i] = i;          
            fp = fopen("exam", "w");          
            fwrite(binary_data, sizeof(binary_data), i, fp);          
            fclose(fp);          
}          

The C programme writes 1024 32-chip integers to a file using C fwrite(). The Fortran 95 reader reads them once as an array, and then reads them individually going backwards through the file. The pos= specifier in the 2d read statement illustrates that positions are in bytes, starting from byte 1 (equally opposed to C, where they get-go from byte 0).

two.5 Internal Files

An internal file is an object of type Graphic symbol such as a variable, substring, array, element of an array, or field of a structured tape. Internal file READ can be from a constant character cord. I/O on internal files simulates formatted READ and WRITE statements by transferring and converting data from i graphic symbol object to another data object. No file I/O is performed.

When using internal files:

  • The name of the character object receiving the data appears in place of the unit number on a WRITE statement. On a READ argument, the proper noun of the character object source appears in place of the unit of measurement number.
  • A abiding, variable, or substring object constitutes a single record in the file.
  • With an assortment object, each assortment element corresponds to a tape.
  • Direct I/O on internal files. (The Fortran 95 standard includes only sequential formatted I/O on internal files.) This is like to direct I/O on external files, except that the number of records in the file cannot be changed. In this case, a record is a unmarried chemical element of an array of graphic symbol strings. This non-standard extension is simply available in FORTRAN 77 compatibility mode by compiling with the -f77 flag.
  • Each sequential READ or WRITE statement starts at the starting time of an internal file.

Example: Sequential formatted read from an internal file (one record just):

demo%            cat intern1.f          
            CHARACTER 10*80          
            READ( *, '(A)' ) X          
            READ( Ten, '(I3,I4)' ) N1, N2 !            This codeline reads the internal file            10          
            WRITE( *, * )  N1, N2          
            END          
demo%            f95 -o tstintern intern1.f          
demo%            tstintern          
                          12 99          
            12 99          
demo%          

Case: Sequential formatted read from an internal file (three records):

demo%            cat intern2.f          
            Graphic symbol  LINE(4)*xvi          
            DATA  LINE(1) / ' 81  81 ' /          
            DATA  LINE(ii) / ' 82  82 ' /          
            Information  LINE(3) / ' 83  83 ' /          
            DATA  LINE(4) / ' 84  84 ' /          
            READ( LINE,'(2I4)') I,J,K,L,M,N          
            PRINT *, I, J, K, L, M, N          
            END          
demo%            f95 intern2.f          
demo%            a.out          
            81  81  82  82  83  83          
demo%          

Case: Direct access read from an internal file (ane record), in -f77 compatibility way:

demo%            true cat intern3.f          
            Character LINE(4)*xvi          
            DATA  LINE(1) / ' 81  81 ' /          
            DATA  LINE(2) / ' 82  82 ' /          
            DATA  LINE(3) / ' 83  83 ' /          
            Data  LINE(iv) / ' 84  84 ' /          
            READ ( LINE, FMT=20, REC=three ) M, Due north          
20       FORMAT( I4, I4 )          
            Impress *, M, N          
            Finish          
demo%            f95 -f77 intern3.f          
demo%            a.out          
            83  83          
demo%          

2.6 Additional I/O Considerations

Fortran 95 and legacy Fortran 77 programs are I/O uniform. Executables containing intermixed f77 and f95 compilations can practise I/O to the same unit of measurement from both the f77 and f95 parts of the programme.

However, Fortran 95 provides some boosted features:

  • Advance='NO' enables nonadvancing I/O, every bit in:
  •               write(*,'(a)',Accelerate='NO')  'Enter size= '            
                  read(*,*) n            

  • NAMELIST input features:
    • f95 allows the grouping name to be preceded by $ or & on input. The Fortran 95 standard accepts but & and this is what a NAMELIST write outputs.
    • f95 accepts $ as the symbol terminating an input group unless the last data item in the group is Grapheme, in which case the $ is treated every bit input data.
    • f95 allows NAMELIST input to start in the beginning column of a tape.
  • ENCODE and DECODE are recognized and implemented by f95 just as they were by f77.

See the Fortran User's Guide for boosted information about Fortran 95 I/O extensions and compatibility between f95 and f77.

andersontheshe.blogspot.com

Source: https://docs.oracle.com/cd/E19059-01/stud.9/817-6694/2_io.html

0 Response to "Reading Variables From a File in Fortran"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel