在Fortran

时间:2017-03-23 17:56:09

标签: fortran

我的问题是我想通过使用文件的扩展名来查询Fortran中的未知文件名。

示例:文件夹中的文件扩展名为" *。cel",扩展名始终相同,但文件名可能不同,因为最终用户会给出。我想检测文件夹中是否存在* .cel并获取文件的名称。

2 个答案:

答案 0 :(得分:1)

简单回答:我担心你无法在标准的Fortran中做到这一点。您将不得不查看您的编译器文档,以查找它是否支持您可以实现所需的扩展。

答案 1 :(得分:1)

这种文件系统交互有点困难。你认为有人会为此创建一个模块,但是很少有,我没有遇到过易于使用的模块。

大多数人要么使用对systemexecute_command_line子程序的特定调用来让shell完成工作,请参见此处:

program my_ls

    use iso_fortran_env
    implicit none
    character(len=*), parameter :: ls_file = '/tmp/my_ls.tmp'
    integer :: u, ios
    character(len=30) :: filename

    call execute_command_line('ls -1 > '//ls_file, wait=.TRUE., exitstat=ios)
    if (ios /= 0) stop "Unable to get listing"

    open(newunit=u, file=ls_file, iostat=ios, status="old", action="read")
    if ( ios /= 0 ) stop "Error opening listing file "

    do
        read(u, *, iostat=ios) filename
        if (is_iostat_end(ios)) exit
        if (ios /= 0) STOP "Unexpected error while reading listing file"
        if (index(filename, ".cel") > 0) then
            print*, filename
        end if
    end do

    close(u)

    call execute_command_line('rm '//ls_file, wait=.FALSE.)

end program my_ls

但更容易的是在启动程序时将文件名作为命令行参数:

program my_ls2

    use iso_fortran_env
    implicit none

    integer :: num_files, i
    character(len=64), allocatable :: filenames(:)

    num_files = command_argument_count()
    allocate(filenames(num_files))
    do i = 1, num_files
        call get_command_argument(i, filenames(i))
    end do

    write(*, '(A)') filenames

end program my_ls2

使用

调用此程序
$ my_ls2 *.cel

会为您提供所需的每个文件。

相关问题