How to Resolve Incorrect Fortran Read from Data Text File?

I have a text file with two numbers on the same line

108  6.7522

I have a fortran subroutine READCN that stores the numbers 108 6.7522 from the text file into the variables NN and BOX

    SUBROUTINE READCN ( CNFILE, BOX )
    CHARACTER   CNFILE*(*)
    REAL        BOX
    INTEGER     CNUNIT
    PARAMETER ( CNUNIT = 10 )
    INTEGER     NN
    OPEN ( UNIT = CNUNIT, FILE = CNFILE, STATUS = 'OLD',
 :         FORM = 'UNFORMATTED'                        )

    READ ( CNUNIT ) NN, BOX
    WRITE(*,*) NN, BOX
    CLOSE ( UNIT = CNUNIT )
    RETURN
    END

The output for READCN variables NN BOX is

   3.2997999      2.74554597E-31

How do I read the values correctly?

This program is taken from

When I attempted to remove the format option in the read command this was the follow error I received

At line 686 of file MCNPT.f (unit = 10, file = 'LATTICE-256.txt')
Fortran runtime error: Missing format for FORMATTED data transfer
1

1 Answer

Moving from using unformatted input to formatted input requires three actions:

  • changing the input to a "text file";
  • opening the file for formatted, rather than unformatted, I/O;
  • providing a format for the read statements.

You've done the first two of these. [If you didn't know, removing form='unformatted' means that the default of formatted I/O is used.]

All that remains is to use a format specifier in the subsequent reads. This is where the compiler is complaining.

The simplest formatted read to use is list-directed, which is given by fmt=* specifier in the read. This should be sufficient for your case, but you should ensure you are happy with its limitations.

To be precise: replace

      OPEN ( UNIT = CNUNIT, FILE = CNFILE, STATUS = 'OLD',
     :         FORM = 'UNFORMATTED'                        )
      READ ( CNUNIT ) NN, BOX

with

      OPEN ( UNIT = CNUNIT, FILE = CNFILE, STATUS = 'OLD')
      READ ( CNUNIT, * ) NN, BOX
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest