首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修改Fortran代码以编写文件、运行可执行文件和从文件中读取数组

修改Fortran代码以编写文件、运行可执行文件和从文件中读取数组
EN

Stack Overflow用户
提问于 2014-07-01 16:01:01
回答 2查看 953关注 0票数 1

我刚接触过Fortran,但我正在尝试修改Fortran代码,而且我在做一些我认为可能很简单的事情时遇到了困难。

我想调整一个名为staral.f的Fortran文件,以便它生成一个名为input.inp的输入文件,并将其填充到原来的.f中计算的4个整数中,以便input.inp看起来像:

代码语言:javascript
复制
    &input
        A = 1
        B = 2
        C = 3
        D = 4
    &end

我知道如何写这种格式:

代码语言:javascript
复制
    OPEN(UNIT=10,FILE='input.inp')
    WRITE (10,00001) 1,2,3,4
    ...
    ...
    ...
    00001 Format (/2x,'&input',
         &        /2x,'A = ',i4,
         &        /2x,'B = ',i4,
         &        /2x,'C = ',i4,
         &        /2x,'D = ',i4,
         &        /2x,'&end')

(或者这样的东西,当我开始工作时,我可以摆弄它),但是我不知道如何创建input.inp文件,把它写进去,然后使用这个输入文件。

需要使用输入文件来运行名为"exec“的可执行文件。我会在bash中这样做:

代码语言:javascript
复制
    ./exec < input.inp > output.out

其中output.out包含两个数组,分别命名为eg(11)和ai(11,6,2) (给定的维数)如下:

代码语言:javascript
复制
    eg(1)= 1
    eg(2)= 2
    ...
    ...
    ...
    eg(11)= 11
    ai(1,1,1)= 111
    ai(1,2,1)= 121
    ...
    ...
    ...
    ai(11,6,2)=1162

最后,我需要将这些输入读入原始.f中,以便在文件中更深入地使用它们。我在原始.f开始时将这些数组定义为:

代码语言:javascript
复制
    COMMON /DATA  / eg(11),ai(11,6,2)

但是,我不确定Fortran是否可以从output.out中读取数据行来填充这些数组。

对这一过程中的任何阶段的任何帮助都将是非常感谢的。

非常感谢

詹姆斯

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-02 20:11:35

如果我正确地理解了扩展的问题,那么您必须使用一个输出文件,该文件是由您没有编写的其他代码生成的,并带有像eg(1) = ...这样的行。

在最简单的情况下,您可以事先知道元素的数量及其顺序,只需从后面搜索每一行的等号:

代码语言:javascript
复制
program readme
  implicit none
  character(100) :: buffer
  integer :: i, j, k, pos, eg(11), ai(11,6,2)

  do i = 1,11
    read*, buffer
    pos = index(buffer, '=', back = .true.)
    read(buffer(pos+1:), *) eg(i)
  enddo

  ! I have assumed an arbitrary ordering here
  do k = 1,2
    do i = 1,11
      do j = 1,6
        read*, buffer
        pos = index(buffer, '=', back = .true.)
        read(buffer(pos+1:), *) ai(i,j,k)
      enddo
    enddo
  enddo 
end program

为了简单起见,这里假设数据是提供给标准输入的。

票数 0
EN

Stack Overflow用户

发布于 2014-07-01 16:41:16

既然您已经展示了如何创建输入文件,我想问题是如何读取它。代码显示了跳过第一行后如何从连续的行中读取"a“和"b”。在Windows上,如果得到的可执行文件是a.exe,则命令a.exe < data.txt或键入data.txt \ a.exe将从data.txt读取。

代码语言:javascript
复制
program xread
implicit none
character (len=10) :: words(3)
integer, parameter :: iu = 5 ! assuming unit 5 is standard input
integer            :: a,b
read (iu,*) ! skip line with &input
read (iu,*) words ! read "a", "=", and "1" into 3 strings
read (words(3),*) a ! read integer from 3rd string
read (iu,*) words ! read "b", "=", and "1" into 3 strings 
read (words(3),*) b ! read integer from 3rd string
print*,"a =",a," b =",b
end program xread
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24514728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档