function get_current_directory() result(cwd) character(len=:), allocatable :: cwd character(len=512) :: pwd_env integer :: status, unit, iostat ! First try environment variable call get_environment_variable('PWD', pwd_env, status=status) if (status == 0) then cwd = trim(pwd_env) return end if ! Try getting current directory via system command block character(len=:), allocatable :: temp_file, pwd_cmd, rm_cmd temp_file = join_path(get_system_temp_dir(), 'fortran_pwd.tmp') if (get_os_type() == OS_WINDOWS) then pwd_cmd = 'cd > "'//escape_quotes(temp_file)//'"' rm_cmd = 'del /f "'//escape_quotes(temp_file)//'"' else pwd_cmd = 'pwd > "'//escape_quotes(temp_file)//'"' rm_cmd = 'rm -f "'//escape_quotes(temp_file)//'"' end if call execute_command_line(pwd_cmd, wait=.true.) open (newunit=unit, file=temp_file, status='old', iostat=iostat) if (iostat == 0) then read (unit, '(A)', iostat=iostat) pwd_env close (unit) call execute_command_line(rm_cmd, wait=.true.) if (iostat == 0) then cwd = trim(pwd_env) return end if end if end block ! Ultimate fallback cwd = '.' end function get_current_directory