在 FORTRAN 中创建名称中包含实数的目录



在我的程序中,我需要存储不同情况的结果文件。我决定创建单独的目录来存储这些结果文件。要解释这里的确切情况是一个伪代码。

do i=1,N     ! N cases of my analysis
    U=SPEED(i)
    call write_files(U)     !Create a new directory for this case and Open files (1 = a.csv, 2 = b.csv) to write data
    call postprocess()      !Write data in files (a.csv, b.csv)
    call close_files()      !Close all files (1,2)
end do
subroutine write_files(i)
    !Make directory i
    !Open file a.csv and b.csv with unit 1 & 2
    !Write header information in file a.csv and b.csv
close subroutine

我正在努力将真正的变量 u 转换为字符变量,以便我可以使用 call system('mkdir out/' trim(U)) 创建单独的文件夹来存储我的结果。

我还想提一下,我的变量 U 是速度,就像0.00000, 1.00000, 1.50000等。有没有办法简化我的目录名称,让它像0,1,1.5等。

希望我的解释清楚。如果没有让我知道,我将尝试根据需要进行编辑。

谢谢你的帮助。

system 的参数需要是一个字符串。因此,您必须将real转换为字符串,并将mkdir out/与该字符串连接起来。下面是一个快速示例:

module dirs 
contains
  function dirname(number)
    real,intent(in)    :: number
    character(len=6)  :: dirname
    ! Cast the (rounded) number to string using 6 digits and
    ! leading zeros
    write (dirname, '(I6.6)')  nint(number)
    ! This is the same w/o leading zeros  
    !write (dirname, '(I6)')  nint(number)
    ! This is for one digit (no rounding)
    !write (dirname, '(F4.1)')  number
  end function
end module
program dirtest
  use dirs
  call system('mkdir -p out/' // adjustl(trim( dirname(1.) ) ) )
end program

您可以使用 Fortran 2008 语句execute_command_line(如果您的编译器支持它),而不是非标准的call system(...)

call execute_command_line ('mkdir -p out/' // adjustl(trim( dirname(1.) ) ) )

最新更新