`错误:打开文件以读取

时间:2017-01-02 10:53:52

标签: fortran gfortran

rogram readfromfile
  implicit none
    integer :: N, i
    integer, dimension(130,2) :: cs

  OPEN (UNIT=20,FILE='readtry.txt',STATUS='OLD',FORM='UNFORMATTED',)
    do i=1,130
    read (*,*) cs(i,1), cs(i,2)
    enddo


    do i=1,130
        print *, cs(i,1), cs(i,2)
    enddo

我是编程的初学者,我只想从一个有两列和大约130行的文件中读取数据。我曾试图写下这段代码,但它不起作用可以有人请求帮助吗?

出现以下错误

gfortran -Wall -c "Rwarray.f95" (in directory: D:\Fortrandir\2Darrays)
Rwarray.f95:7:67:
   OPEN (UNIT=20,FILE='readtry.txt',STATUS='OLD',FORM='UNFORMATTED',)
                                                                   1
Error: Syntax error in OPEN statement at (1)
Compilation failed.

1 个答案:

答案 0 :(得分:1)

您有编译时错误,而不是读取问题。但这是它的要点:

它抱怨语法错误。你的陈述是这样的:

open(xxx, xxx, xxx, xxx,)

为了编译它,您需要删除最后一个逗号。但我不认为这会给你你想要的东西。

当您打开文件时,声明它是未格式化的。 Unformatted基本上意味着它包含某种形式的二进制值。更重要的是,未格式化的计算机之间无法保证可以正常工作。因此,除非使用FORM="UNFORMATTED"参数通过Fortran程序在您的系统上编写此文件,否则我认为您不会得到您想要的内容。

我怀疑你的输入文件是这样的:

1   3
2   10
31  4711

那将是FORMATTED,而不是UNFORMATTED

然后使用read(*, *)。但是第一个*指的是"标准输入",如果你想从文件中读取,你想使用read(20, *),因为20是你的单位打开输入文件。

对于write语句,*是正确的,假设您要写入"标准输出" - 即屏幕。

我还建议使用错误处理例程。将这两个变量添加到声明块中:

integer :: ios
character(len=100) :: iomsg

然后在打开,阅读或书写时使用它们:

open(unit=xx, file=xxx, status=xxx, action=xxx, form=xxx, io_stat=ios, iomsg=iomsg)
call check(ios, iomsg, "OPEN")

read(20, *, io_stat=ios, iomsg=iomsg) cs(1, i), cs(2, i)
call check(ios, iomsg, "READ")

您必须包含check子例程,当然:

program readfromfile
    implicit none
    <declaraction block>
    <execution block>
contains
    subroutine check(ios, iomsg, action)
        integer, intent(in) :: ios
        character(len=*), intent(in) :: iomsg
        character(len=*), intent(in), optional :: action
        if (ios == 0) return  ! No error occured, return
        print*, "Error found. Error code:", ios
        print*, "Message: ", trim(iomsg)
        if (present(action)) print*, "Action was: ", trim(action)
        stop 1
    end subroutine check
end program readfromfile
相关问题