nat*_*lng 7 directory gcc fortran intel-fortran
我希望更改 Fortran 90 代码中的工作目录。是否可以以非特定于编译器的方式执行此操作?这是我的代码:
program change_directory
integer :: ierr
call system("mkdir -p myfolder/")
!call system("cd myfolder/") !doesn't work
ierr = chdir("myfolder")
if (ierr.NE.0) then
write(*,'(A)') "warning: change of directory unsuccessful"
end if
open(unit=33,file="myfile.txt",iostat=ierr)
if (ierr.EQ.0) then
write(unit=33,fmt='(A)') "Test message"
close(unit=33)
end if
end program change_directory
Run Code Online (Sandbox Code Playgroud)
显然,cd myfolder/在系统调用中使用是行不通的。英特尔参考资料说我需要添加“ use ifport”。不过, GCC 参考文献中没有这样的提及。省略“ ”,我可以毫无问题地use ifport编译上面的代码。ifort然而,当我把它放进去时,它不会用 gcc 编译(因为 gcc 没有该ifport模块)——不仅如此,它也不会在 Intel Fortran 下编译——我收到以下错误:
$ ifort change_dir.f90 -o change_dir
change_dir.f90(5): error #6552: The CALL statement is invoking a function subprogram as a subroutine. [SYSTEM]
call system("mkdir -p myfolder/")
---------^
compilation aborted for change_dir.f90 (code 1)
Run Code Online (Sandbox Code Playgroud)
所以我的问题如下:有没有更好的方法来做到这一点?我想让我的代码尽可能独立于编译器。目前,我主要使用 gfortran/ifort 和 mpif90/mpiifort。
另请参阅有没有办法使用 C 语言更改目录?。您可以使自己的chdir() POSIX 调用接口独立于 Intel 的接口。在 Windows 上也是类似的。
module chdir_mod\n\n implicit none\n\n interface\n integer function c_chdir(path) bind(C,name="chdir")\n use iso_c_binding\n character(kind=c_char) :: path(*)\n end function\n end interface\n\ncontains\n\n subroutine chdir(path, err)\n use iso_c_binding\n character(*) :: path\n integer, optional, intent(out) :: err\n integer :: loc_err\n\n loc_err = c_chdir(path//c_null_char)\n\n if (present(err)) err = loc_err\n end subroutine\nend module chdir_mod\n\n\nprogram test\n\n use chdir_mod\n\n call chdir("/")\n\n call system("ls -l")\n\nend\nRun Code Online (Sandbox Code Playgroud)\n\n当运行时
\n\n> gfortran chdir.f90 \n> ./a.out \ncelkem 120\ndrwxr-xr-x 2 root root 4096 15.\xc2\xa0\xc5\x99\xc3\xadj 14.42 bin\ndrwxr-xr-x 5 root root 4096 15.\xc2\xa0\xc5\x99\xc3\xadj 14.43 boot\n...\nRun Code Online (Sandbox Code Playgroud)\n\n在ifort它上也可以像在 上一样工作sunf90。
(注意:这依赖于默认值character与 相同c_char。这是一个相当安全的假设。如果不是这种情况,编译器会抱怨并且必须进行转换。)