Input Output

Formats and Files

Formatted I/O

•     only simple input output statements used

•     output printed is not readable

•     formatted output used to print output in required form

•     formatted input can also be used

•     print only required number of decimal places

•     leave appropriate spaces and alignment

•     write/read data to/from files to store it permanently

Format

•     format is a character string which specifies the way each item is to be printed

•     a format string contains “edit descriptors”

•     each edit descriptor describes the way the corresponding item is to be read/printed

print “(i4)”, i

•     * in print is replaced by a format string

•     i4 is an edit descriptor that specifies that an integer must be printed in first 4 columns

•     value of i printed with units digit in 4th column

Format

•     format string must specify an edit descriptor for each item to be printed or read

print “(i4,2x,f6.3,2x,i6)” ,  i, x, j

•     3 items to be printed on one line

•     first 4 columns used for printing integer i

•     x is an edit descriptor which specifies that a column must be left blank (2 before it indicates that it is repeated 2 times)

•     f6.3 is an edit descriptor for “real” numbers

•     6 columns used and 3 decimal places printed

Format String

•     general form of a format string (can be a character variable)

•     “(e1, e2, ….., ek  where each ei is an edit descriptor

•     some edit descriptors associated with items to be read or printed

•     association is done in sequence from left to right

•     other edit descriptors used to determine spacing and position on line to be read/printed

•     line usually assumed to contain 80 columns

 

Edit Descriptors

•     Fortran has a wide variety of edit descriptors

•     iw -  indicates w columns used for printing corresponding integer (including one column for sign, if negative)

•     fw.d – used for printing a real number with fixed decimal point – w columns total and d decimal places

•     ew.d – real number in exponential notation with w columns and d decimals in mantissa

Edit Descriptors

•     aw – character string of length w

•     lw -  w columns for a logical value ( T or F)

•     x  -  leave a blank column

•     tn – (used for tabulation) read/print from column number n from current line

•     trn – move n places to the right on current line

•     tln – move n places left of current position

•     / - read/print from/to next line

Edit Descriptors

•     edit descriptors grouped by inserting brackets

•     repeated by prefixing with an integer constant (a group may be also be repeated)

•     if columns provided in edit descriptors are insufficient , value will not be printed

print “(i4)”, 23456 will print out  ****

•     character strings would be truncated

•     if insufficient edit descriptors are provided the group after rightmost left bracket is repeated and remaining values printed on new line

Example

•     print an integer array 10 values per line

print “(10i4)”, a(1:n)

•     each element of a is printed using 4 columns

•     after 10 values are printed, same format applied on a new line

•     excess edit descriptors are ignored

print “(a15, (t20,10i4))”,  “the matrix is”,          &

                                      (a(i,1:10), i = 1,10)

•     prints matrix from 20th column one row per line

Files

•     used keyboard for input, terminal for output

•     inadequate if input or output data is large

•     data is not stored “permanently”

•     entered again for every run of program

•     output of one program cannot be directly fed to another program

•     data cannot be entered “offline”

•     files can be used to do all of these

Files

•     data stored on hard disk in the form of files

•     a file consists of a sequence of “records”

•     file identified by a name and created using an editor like pico or vi (one record per line)

•     such files can be used to store program data

•     data can be read from and written to such files directly by a Fortran program

•     Fortran has powerful statements for input output from files

 

Open Statement

•     files on the hard disk are associated with a integer unit number  in a Fortran program

•     usually unit number is between 1 to 100

•     open statement creates the association

open(unit=10, file=“input.dat”)

•     associates unit 10 with file named input.dat

•     input output on unit 10 actually performs the operation on file named input.dat

•     file name can be a character variable

File Attributes

•     file attributes specified in open statement

•     status

–   can be “old”, “new”, “replace”, “scratch”

–   indicates whether it is an existing file

•     access

–   can be “sequential” or “direct”

–   records of sequential files accessed in order from the beginning

–   specified record can be accessed in direct access files

File Attributes

•     action

–   “read”, “write”, or “readwrite”

•     form

–   “formatted” or “unformatted”

–   unformatted files contain data in internal representation, cannot be edited

•     recl

–   length of each record (number of characters)

–   required for direct access files

Example

open(unit=10, file=“input.dat”, statusold”,  & accesssequential”, actionread”, iostat &

  =ios, form = “formatted”, positionrewind”)

•     ios is an integer variable which gets non-zero value if open fails

•     position specifies current record for old files

–   “rewind” means first record, “append” means after the last record

•     opens a sequential, formatted file input.dat for reading

 

Input Output From Files

•     once a file is opened it can be used for i/o

read(unit=10, fmt=“(i4)”, iostat=ios) number

•     reads an integer (number) from unit 10, i.e. first line of file input.dat using format i4

•     ios is an integer variable used to indicate status of read, non-zero on error like end of file

•     after reading one record, file is advanced to next record, can specify advance = “no” in read

•     unit = * or fmt = * uses default values

Input Output From Files

open(unit=11,file=“output.dat”, statusnew”,&

accessdirect”, formformatted”, iostat=   &

ios, recl = 30, actionwrite”)

•     creates a new direct access file output.dat whose records can be written

write(unit=11,fmt=“(i6)”,rec=10,iostat=ios) i

•     writes integer i with format “i6” in record number 10 of file output.dat

File Functions

•     intrinsic functions for files

•     close(unit=i) – closes file associated with unit i

–   always close files before program stops

•     rewind(unit=i), backspace(unit=i)

–   rewind goes to first record while backspace goes back one record ( sequential file)

•     endfile(unit=i)

–   puts end of file mark without closing file

•     inquire(unit=i) – used for getting file properties

Example

program check_user

implicit none

character(len=30) :: address

character(len=8) :: username

logical :: err, valid

call get_address(address)

call get_username(address,username,err)

if (err) then

     print *, "invalid address   " , address

else

    call verify_user(username,valid)

    if (valid) then

          print *, "username is valid"

    else

           print *, "invalid user   ", username

    endif

endif

contains

   subroutine get_address(address)

   character(len=*),intent(out) :: address

   print *, "enter email address"

   read *,  address

   end subroutine get_address

 

   subroutine get_username(address,username,err)

   character(len=*),intent(in) :: address

   character(len=*), intent(out) :: username

   logical, intent(out) :: err

   character(len=len(address)) :: temp

   integer :: i

   temp =adjustl(address)

   err = .false.

   i =  scan(temp, "@")

   if ((i == 0) .or. ( i > 8)) then

        err = .true.

   else

        username = temp(1:i-1)

   endif

   end subroutine get_username

 

   subroutine verify_user(username,valid)

   character(len=*), intent(in) :: username

   character(len=len(username)) :: user

   logical,intent(out) :: valid

   integer :: ios

   valid = .false.

    open(unit=11,file="usernames",status="old",            &

    accesssequential”, action="read", form=             &

    "formatted", position="rewind", iostat=ios)

    if ( ios /= 0) return

    do

      read(unit=11,fmt=*,iostat=ios) user

      if ( ios /= 0) exit

      if ( user == username) then

          valid = .true.

          exit

      elseif (user > username) then

          exit

      endif

  end do

  close(unit=11)

  end subroutine verify_user

end program check_user