简体   繁体   English

在Fortran中读取ASCII文件

[英]Reading an ASCII File in Fortran

I have a question. 我有个问题。 I have an ASCII FILE full of numbers on my desktop but I need to know how to read the ASCII FILE using FORTRAN. 我的桌面上有一个充满数字的ASCII文件,但是我需要知道如何使用FORTRAN读取ASCII文件。 Can you show me an example of how its done or what command that is? 您能给我看一个例子,说明它是如何完成的或者是什么命令?

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, ie 假设您的文件包含3列浮点数,即

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. 遗憾的是,这需要对文件进行初步检查,因为Fortran不会提供不断增长的阵列,而且自己实施替换操作很不方便。 Assuming you use fortran 90 or newer, this would look something like this: 假设您使用的是fortran 90或更高版本,则看起来像这样:

    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. 定义类似getlun()的函数很常见,该函数将为您提供一个免费的单元号。 A quick google search produced this: http://ftp.cac.psu.edu/pub/ger/fortran/hdk/getlun.f90 . 快速的Google搜索产生了以下内容: 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". 如果您有足够新的编译器,则可以使用open(newunit = unit,...),它将自动为变量“ unit”分配一个空闲的单元号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM