|
| 1 | +module ioutils |
| 2 | +implicit none |
| 3 | +contains |
| 4 | + |
| 5 | +subroutine expanduser(expandhome, indir) |
| 6 | + |
| 7 | +character(*), intent(in), optional :: indir |
| 8 | +character(:), allocatable, intent(out) :: expandhome |
| 9 | + |
| 10 | +character :: filesep |
| 11 | +character(256) :: buf |
| 12 | +! -- resolve home directory as Fortran does not understand tilde |
| 13 | +! works for Linux, Mac, Windows and more |
| 14 | + |
| 15 | +if (present(indir)) then |
| 16 | + if (indir(1:1) /= '~') then |
| 17 | + expandhome = indir |
| 18 | + return |
| 19 | + endif |
| 20 | +endif |
| 21 | + |
| 22 | +! assume MacOS/Linux/BSD/Cygwin/WSL |
| 23 | +filesep = '/' |
| 24 | +call get_environment_variable("HOME", buf) |
| 25 | + |
| 26 | +if (len_trim(buf) == 0) then ! Windows |
| 27 | + call get_environment_variable("USERPROFILE", buf) |
| 28 | + filesep = char(92) |
| 29 | +endif |
| 30 | + |
| 31 | +expandhome = trim(buf) // filesep // indir(3:) |
| 32 | + |
| 33 | + |
| 34 | +end subroutine expanduser |
| 35 | + |
| 36 | +end module ioutils |
| 37 | + |
| 38 | +!------ demo |
| 39 | + |
| 40 | +program home |
| 41 | + |
| 42 | +use ioutils |
| 43 | +implicit none |
| 44 | +! explores what '~' means for paths in Fortran |
| 45 | +! Note: when testing, enclose argument in '~/test.txt' quotes or |
| 46 | +! shell will expand '~' before it gets to Fortran! |
| 47 | + |
| 48 | +integer :: fid, ios |
| 49 | +character(:), allocatable :: expanded |
| 50 | +character(256) :: buf |
| 51 | + |
| 52 | +call get_command_argument(1, buf, status=ios) |
| 53 | + |
| 54 | +if (ios==0) then |
| 55 | + call expanduser(expanded, trim(buf)) |
| 56 | +else |
| 57 | + call expanduser(expanded) |
| 58 | +endif |
| 59 | + |
| 60 | +print '(A)', trim(buf) |
| 61 | +print '(A)', expanded |
| 62 | + |
| 63 | +end program |
0 commit comments