Get terminal window size from Fortran

less than 1 minute read

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.

Working example

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

Non-working example

Use the method above, as the method below naively 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

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

Leave a comment