1- module ioutils
1+ module fsutils
22implicit none
33contains
44
5- subroutine expanduser (expandhome , indir )
5+ function expanduser (indir )
66
7- character (* ), intent ( in ), optional :: indir
8- character (: ), allocatable , intent (out ) :: expandhome
7+ character (: ), allocatable :: expanduser
8+ character (* ), intent (in ) :: indir
99
10- character :: filesep
11- character (256 ) :: buf
1210! -- resolve home directory as Fortran does not understand tilde
1311! works for Linux, Mac, Windows and more
1412
15- if (present (indir)) then
16- if (indir(1 :1 ) /= ' ~' ) then
17- expandhome = indir
18- return
19- endif
13+ if (len (indir) < 1 ) then
14+ stop ' must provide path to expand'
15+ elseif (indir(1 :1 ) /= ' ~' ) then
16+ expanduser = indir
17+ return
18+ elseif (len (indir) < 3 ) then
19+ expanduser = homedir()
20+ else
21+ expanduser = homedir() // indir(3 :)
2022endif
2123
24+ end function expanduser
25+
26+
27+ function homedir ()
28+
29+ character (:), allocatable :: homedir
30+ character :: filesep
31+ character (256 ) :: buf
32+
2233! assume MacOS/Linux/BSD/Cygwin/WSL
2334filesep = ' /'
2435call get_environment_variable(" HOME" , buf)
@@ -28,34 +39,29 @@ subroutine expanduser(expandhome, indir)
2839 filesep = char (92 )
2940endif
3041
31- expandhome = trim (buf) // filesep // indir( 3 :)
42+ homedir = trim (buf) // filesep
3243
44+ end function homedir
3345
34- end subroutine expanduser
3546
36- end module ioutils
47+ end module fsutils
3748
3849!- ----- demo
3950
4051program home
4152
42- use ioutils
53+ use fsutils
4354implicit none
4455! explores what '~' means for paths in Fortran
4556! Note: when testing, enclose argument in '~/test.txt' quotes or
4657! shell will expand '~' before it gets to Fortran!
4758
48- integer :: fid, ios
4959character (:), allocatable :: expanded
5060character (256 ) :: buf
5161
52- call get_command_argument(1 , buf, status = ios )
62+ call get_command_argument(1 , buf)
5363
54- if (ios== 0 ) then
55- call expanduser(expanded, trim (buf))
56- else
57- call expanduser(expanded)
58- endif
64+ expanded = expanduser(trim (buf))
5965
6066print ' (A)' , trim (buf)
6167print ' (A)' , expanded
0 commit comments