Search code examples
directoryfortrancreate-directory

How to create a new directory from Force Fortran 2.0


I need to create a new directory from my code to be able to write a data file to it.

I am using Force Fortran 2.0 from Windows 8 and I am also wondering if this syntax is going to vary from one operating system to the other due to the front/backslash issue.


Solution

  • Force Fortran uses older compilers (g77, g95, gfortran [unknown version]), so I'll present a solution with system. For compilers that support it, it's better to use the Standard-conforming EXECUTE_COMMAND_LINE.

    You can simply use mkdir, which is present on both Windows and Unix machines. By default, mkdir creates the folder and (non-existing) parent folders on Windows. This has to be explicitly given on Unix (-p). Using system you can execute this from Fortran:

    program test
      implicit none
    #ifdef _WIN32
      character(len=*),parameter :: MKDIR = 'mkdir '
      !                                           ^
      !                    The blank is intentional! 
    #else
      character(len=*),parameter :: MKDIR = 'mkdir -p '
      !                                              ^
      !                       The blank is intentional! 
    #endif
      integer :: stat
    
      stat = system( MKDIR // 'testFolder' )
      if ( stat /= 0 ) then
        print *, 'mkdir: failed to create folder! '
      endif
    end program
    

    You still need to create a routine that takes care of the correct folder delimiter, here is a quick&dirty example:

    module conv_mod
    contains
      function conv2win(str) result(res)
        implicit none
        character(len=*),intent(in) :: str
        character(len=len(str))     :: res
        integer                     :: i
    
        res = str
        do i=1,len(res)
          if ( res(i:i) == '/' ) res(i:i) = '\'
        enddo ! i
      end function
    
      function conv2unix(str) result(res)
        implicit none
        character(len=*),intent(in) :: str
        character(len=len(str))     :: res
        integer                     :: i
    
        res = str
        do i=1,len(res)
          if ( res(i:i) == '\' ) res(i:i) = '/'
        enddo ! i
      end function
    end module
    
    program conv
      use conv_mod
      print *,conv2win('some/path')
      print *,conv2win('some\path')
      print *,conv2unix('some\path')
    end program
    

    This doesn't take care of things like C:\, though... As @VladimirF noted, you can use / in Windows, too. You would still need to convert the backslash to / in Unix.