fortrangfortranfortran2003fortran2008

Is there an alternative to GETCWD() in Fortran 2003-2008


The GNU Extension to the GNU Fortran compiler provides the subroutine GETCWD() that well, gets the current working directory. However, my code has to be portable to the ifort and nagfor compiler as well and I use F2003 features.

So, is there an alternative to GETCWD() for F2003 and later?

I have the standard here but it's quite sizeable and I've been going through it for a while now and haven't found anything useful...


Solution

  • You can also use the ISO_C_Binding and call the corresponding C functions:

    cwd.c:

    #ifdef _WIN32
    /* Windows */
    #include <direct.h>
    #define GETCWD _getcwd
    
    #else
    /* Unix */
    #include <unistd.h>
    #define GETCWD getcwd
    
    #endif
    
    void getCurrentWorkDir( char *str, int *stat )
    {
      if ( GETCWD(str, sizeof(str)) == str ) {
        *stat = 0;
      } else {
        *stat = 1;
      }
    }
    

    test.F90:

    program test
     use ISO_C_Binding, only: C_CHAR, C_INT
     interface
       subroutine getCurrentWorkDir(str, stat) bind(C, name="getCurrentWorkDir")
         use ISO_C_Binding, only: C_CHAR, C_INT
         character(kind=C_CHAR),intent(out) :: str(*)
         integer(C_INT),intent(out)         :: stat
        end subroutine
      end interface
      character(len=30)   :: str
      integer(C_INT)      :: stat
    
      str=''
      call getCurrentWorkDir(str, stat)
      print *, stat, trim(str)
    
    end program
    

    This code is valid for Windows and Unix-derivates (Linux, OSX, BSD, etc. )