首页 > 解决方案 > 在 Windows 命令行中使用管道运行简单的 Fortran exe

问题描述

我有一个 Fortran 可执行文件,它在进行计算之前需要几个键盘输入。它在输入输入的终端中工作,但我想使用管道输入输入(Windows 10 命令行)。当我只有一个键盘输入时,管道可以完美运行。我怎样才能让它与多个输入一起工作?

我几乎可以根据这里的类似问题让它工作:将参数传递给交互式 fortran 程序。我查看了有关标准输入的文档,但我仍然无法弄清楚。

这是一个只有一个输入的示例 Fortran 程序,它适用于管道。

      program foo
      integer n
      character*80 c
      
      write (*,*) 'Enter 1,2,3 for cat,dog,fish'
      read (*,*) n
      if (n .eq. 1) then
      write (*,*) 'meow'
      elseif (n .eq. 2) then
      write (*,*) 'woof'
      elseif (n .eq. 3) then
      write (*,*) 'blurp'
      else
      write (*,*) 'error1'
      endif
      
C     write (*,*) 'Enter y,n for yay,nay'
C     read (*,*) c
C     if (c == 'y') then
C     write (*,*) 'yes'
C     elseif (c == 'n') then
C     write (*,*) 'no'
C     elseif (n .eq. 3) then
C     else
C     write (*,*) 'error2'
C     endif

      end

终端测试:

C:\my\file\path> C:\my\file\path\foo.exe
 Enter 1,2,3 for cat,dog,fish
2
 woof

C:\my\file\path> echo 1 | C:\my\file\path\foo.exe
 Enter 1,2,3 for cat,dog,fish
 meow

这是一个具有多个输入的示例 Fortran 程序,它不适用于管道。

与上面相同的程序,但注释行未注释。终端测试:

C:\my\file\path> C:\my\file\path\foo.exe
 Enter 1,2,3 for cat,dog,fish
3
 blurp
 Enter y,n for yay,nay
n
 no

C:\my\file\path> echo 1 y | C:\my\file\path\foo.exe
 Enter 1,2,3 for cat,dog,fish
 meow
 Enter y,n for yay,nay
At line 18 of file C:/my/file/path/foo.f (unit = 5, file = 'stdin')
Fortran runtime error: End of file

Error termination. Backtrace:

Could not print backtrace: libbacktrace could not find executable to open
#0  0x318dd91b
#1  0x318d6b34
#2  0x318d355b
#3  0x318d7f6c
#4  0x318e8e9d
#5  0x318d88df
#6  0x318d5190
#7  0x318b1691
#8  0x318f3f93
#9  0x318b13c0
#10  0x318b14f5
#11  0xb9677c23
#12  0xba24d4d0
#13  0xffffffff

编译器信息: GNU gfortran,基于wiki 示例的 CMake

标签: windowscmdfortranpipegfortran

解决方案


您有两个简单的读取语句。每个读取一条记录 = 一行文本。您需要提供两条记录或让程序在旧记录处继续。

中,我可以echo -e "2 \n y" | ./a.out将两条记录放入一个echo命令中,但我不确定 Windows cmd。在 Powershell 中,您应该使用Echo newline 到 powershell console。这意味着

echo "2 `n y"

如果您可以更改 Fortran 代码,请使用非高级输入:

read (*,'(i1)',advance="no") n

有了这个改变,我可以做到

> echo -e "2 y" | ./a.out 
 Enter 1,2,3 for cat,dog,fish
 woof

在 bash 中测试,但应该在其他地方工作,包括 cmd。


推荐阅读