-->

f90 read .txt file return NaN

2019-09-20 08:40发布

问题:

I am trying to read a .txt file with multiple arrays with a fortran program.

It looks like the program is finding the file but it only returns NaN value...

 !
INTEGER                              :: T, RH, i, j, ierror
!
REAL, DIMENSION(3,3)                 :: AFILE
!
LOGICAL                              :: dir_e

inquire(file='PSR_FAB.txt', exist=dir_e)

if ( dir_e ) then
 print*, "dir exists!"
else
 print*, 'nope'
end if

OPEN (UNIT = 1234 , FILE = 'PSR_FAB.txt', STATUS = 'OLD', ACTION = 'READ')

   DO i=1,3
      READ(1234,*, IOSTAT=ierror) (AFILE(i,j),j=1,3)
       print*, (AFILE(i,j),j=1,3)
!      if (ierror>0) then
!        stop 'Error while reading from file. '
!      elseif (ierror<0) then
!        print* ,PSR_FILE
!        stop 'Reached end of file. '
!      endif
   ENDDO
  CLOSE(UNIT=1234)
!
T=2
RH=3
print*,AFILE(T,RH)
!    

In order to test the program, I'm using the following .txt file:

1 2 3
4 5 6
7 8 9

Also, when I am using the "ierror if test", the "Reaching end of file" pops out, which mean ierror<0, which mean the end of file is reach.

At first I thought it was because it could not find the file, but when I inquire it, it has no problem finding it...

And as I said earlier, the AFILE contains only NaN value after the file has been read.

I am wondering if the problem lies in the .txt file or in the code. Maybe it is the READ statement, but the code seems ok to me.

I am kind of stuck at the moment and out of ideas... Any thoughts?

Thank you

回答1:

I experienced a similar problem when I ran a program on a Windows 2000, but it worked fine on a Windows 7 box.

In my situation, the application was built on a Win7 box using Intel Fortran V11. This application worked on a Win7 box, but when run on a Win2000 box it failed to read the first 2 entries.

Try compiling with the /arch:IA32 option. This will use the X87 instruction set instead of the SSE2 enhanced instructions. This produces an application that works on both platforms.



回答2:

It's possible the PSR_FAB.txt file is being opened at a position that is not the beginning of the file. Without specifying the POSITION= attribute to the open statement the file position is taken ASIS. I'm not certain what conditions result in ASIS yielding a position other than the start of the file, though.

I recommend specifying the file be rewound on opening, with:

 OPEN (UNIT = 1234 , FILE = 'PSR_FAB.txt', STATUS = 'OLD',     &
       ACTION = 'READ', POSITION = 'REWIND')

There are other issues that could cause this problem (or others like it), though.