-1

我有个问题。我的桌面上有一个充满数字的 ASCII 文件,但我需要知道如何使用 FORTRAN 读取 ASCII 文件。你能告诉我它是如何完成的或者是什么命令的例子吗?

4

1 回答 1

3

You didn't give many details, so I'm going to make some assumptions here. Let's say that your file consists of 3 columns of floating point numbers, i.e.

1.2345 -4.222e7 2.229
77.222 77e7     50
...

If you simply want to read these numbers without storing them in an array, this could be done straightforwardly as

    integer :: unit
    real    :: a,b,c
    unit = 20
    open(unit,"foo.txt",status="old",action="read")
    do
        read(unit,*,end=1) a, b, c
        write(*,*) "I got", a, b, c
    end do
    1 close(unit)

If you want to store these numbers as an array, however, you first need to allocate the appropriate amount of space, for which you need to know the number of lines. This requires a preliminary pass through the file, sadly, because Fortran doesn't provide growing arrays, and implementing a replacement yourself is inconvenient. Assuming you use fortran 90 or newer, this would look something like this:

    integer :: unit, i, n
    real, allocatable :: data(:,:)
    unit = 20
    open(unit,"foo.txt",status="old",action="read")
    n = 0
    do
        read(unit,*,end=1)
        n = n+1
    end do
    1 rewind(unit)
    allocate(data(n,3))
    do i = 1, n
        read(unit,*) data(i,:)
    end do
    close(unit)

The unit number is simply some unique user-chosen number. Beware that some low numbers have predefined meanings. It is common to define a function like getlun() that will provide a free unit number for you. A quick google search produced this: http://ftp.cac.psu.edu/pub/ger/fortran/hdk/getlun.f90. If you have a new enough compiler, you can use open(newunit=unit,...) which will automatically assign a free unit number to the variable "unit".

于 2012-10-26T14:32:56.110 回答