Changing a directory in Fortran in a non-specific way
I want to change the working directory in Fortran 90 code. Can I do this outside the compiler? Here is my code:
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
Clearly using cd myfolder/
in a system call doesn't work. Intel link says I need to add. ' use ifport
' However, no mention is made in the GCC link . Leaving " use ifport
" left , I can compile the above code under ifort
without any problem. However, when I paste it in, it won't compile with gcc (because gcc has no module ifport
) - not only that, it also won't compile in Intel Fortran - I get the following error:
$ 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)
So my question is this: is there a better way to do this? I would like to keep my code as compiler independent. At the moment I am using gfortran / ifort and mpif90 / mpiifort.
source to share
See also Is there a way to change directory using C? ... You can make your own interface for chdir()
POSIX calls independent of the Intel interface. On Windows it is similar.
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
and at startup
> 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
...
In ifort
it works the same way as on sunf90
.
(Note: this means the default is the character
same c_char
. This is a pretty safe assumption. If it is not, the compiler will complain and a conversion must be done.)
source to share