Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Get a file's absolute path

efengle
Novice
1,017 Views

Is there a native way in Fortran to get a file's absolute path?  I feel like this should be something you could obtain with INQUIRE but not currently available.

I have spent the last few days trying to interface Fortran with C functions realpath() and canonicalize_file_name() to obtain a file's absolute path but I am having trouble with that -- which will most likely be another post.

Thanks in advance for any help.

3 Replies
Steven_L_Intel1
Employee
1,017 Views

See FULLPATHQQ in the Intel Fortran documentation.

0 Kudos
efengle
Novice
1,017 Views

Thank you Steve for the help.  I try to stay away from Intel's IFPORT module only to try to be Fortran vendor independent (I know I can use preprocessing to determine vendor...etc), but I will use for the time being.  I did however get a working Fortran interface and test program using C realpath().

program test
use, intrinsic :: iso_c_binding
implicit none

! Constants
integer, parameter :: PATH_MAX=1024 ! Safer to get from the system

! Define
integer :: n
character(len=:), allocatable :: file_name
character(len=1) :: a(PATH_MAX)
character(len=PATH_MAX) :: aa
type(c_ptr) :: ptr

! Fortran interface to C function, realpath()
interface
   function realpath(path,resolved_path) bind(c,name="realpath")
   use, intrinsic :: iso_c_binding
   type(c_ptr) :: realpath
   character(len=1,kind=c_char), intent(in) :: path(*)
   character(len=1,kind=c_char), intent(out) :: resolved_path(*)
   end function realpath
end interface

! Initialize
a=""
file_name="./bin/connect"//C_NULL_CHAR

ptr=realpath(file_name,a)

! Transfer character array to character string
aa=transfer(a,aa)

! Determine the first null char
do n=1,PATH_MAX
   if(iachar(aa(n:n)).eq.0) exit
end do

! Print
print *,"File name = ",file_name
print *,"Absolute file name = ",aa(1:n-1)

end program test

 

0 Kudos
Steven_L_Intel1
Employee
1,017 Views

You don't need to do the TRANSFER. You're allowed to pass a non-1-length character variable to an array of characters. This is a special exemption carved out in the standard. Note that no length is passed, so you still have to make sure that the buffer you pass is large enough and that the NUL termination is properly handled.

0 Kudos
Reply