2014-11-04 82 views
2

我希望更改Fortran 90代碼中的工作目錄。有沒有可能以非編譯器特定的方式做到這一點?這裏是我的代碼:以非編譯器特定方式更改Fortran中的目錄

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 

顯然,在一個系統調用使用cd myfolder/不起作用。 Intel reference表示我需要添加'use ifport'。儘管如此,GCC reference中沒有這樣的提及。留下'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) 

所以我的問題是:有沒有更好的方法來做到這一點?我想保持我的代碼儘可能獨立於編譯器。目前,我主要使用gfortran/ifort和mpif90/mpiifort。

回答

1

另請參閱Is there any way to change directory using C language?。您可以使自己的接口與chdir()POSIX call獨立於英特爾的接口。在Windows上它是相似的。

module chdir_mod 

    implicit none 

    interface 
    integer function c_chdir(path) bind(C,name="chdir") 
     use iso_c_binding 
     character(kind=c_char) :: path(*) 
    end function 
    end interface 

contains 

    subroutine chdir(path, err) 
    use iso_c_binding 
    character(*) :: path 
    integer, optional, intent(out) :: err 
    integer :: loc_err 

    loc_err = c_chdir(path//c_null_char) 

    if (present(err)) err = loc_err 
    end subroutine 
end module chdir_mod 


program test 

    use chdir_mod 

    call chdir("/") 

    call system("ls -l") 

end 

和運行時

> gfortran chdir.f90 
> ./a.out 
celkem 120 
drwxr-xr-x 2 root root 4096 15. říj 14.42 bin 
drwxr-xr-x 5 root root 4096 15. říj 14.43 boot 
... 

ifort它的工作原理也因爲它在sunf90

(注:。這依賴於默認character是一樣c_char這是一個相當安全的假設如果不是,編譯器會抱怨的情況和轉換要作出)

相關問題