Get terminal window size from Fortran

The Bash shell has environment variables LINES and COLUMNS representing the current terminal window width. One might therefore incorrectly assume that Fortran 2003 standard get_environment_variable() subroutine would trivially get the current Terminal window dimensions. This is not so, since Bash passes along only the “POSIX” set of environment variables, and those that have been exported to the executable.

A working example of getting current Fortran terminal size using Ncurses is in the BlockTran program, where the variables LINES and COLS are set using the getmaxyx Ncurses macro.


Use the method above, as the method below naïvely fails.

Thus, the following will result in status code 1, indicating the environment variable was not found.

If the user runs this program as

LINES=24 ./myprog

that “works”, but we want an automatically determined value.

program noenv

use, intrinsic:: iso_fortran_env, only: error_unit

implicit none (type, external)

character(4) :: buf
integer :: h,ios

call get_environment_variable('LINES',buf,status=ios)

if (ios/=0) then
  write(error_unit,*) 'got error code',ios,'on trying to get LINES'
  stop
endif

read(buf,*) h

end program