UNIX & GNU/Linux - System calls - Using tgetent()

The tgetent() function is a Linux system call function. It is designed to be used with other termcap functions such as:

  • tgetflag
  • tgetnum
  • tgetstr
  • tgoto
  • tputs

With the tgetent() function, we stock in the first parameter (a buffer pointer), the capabilities of the second parameter (the environment variable retrieved by the getenv() function).
This function returns 1 on success, 0 if there is not a such description and -1 if the terminfo database is not found.

Let's see an example of the tgetent() function with the "TERM" variable and its height and width:

/*                                                                         
** Made by BadproG.com                                                     
*/

#include        <stdio.h>
#include        <curses.h>
#include        <term.h>
#include        <stdlib.h>

int     main()
{
  const char *name;
  char  *bp;
  char  *term;
  int   height;
  int   width;

  bp = malloc(sizeof(*bp));
  name = "TERM";
  if ((term = getenv(name)) == NULL)
    return (1);
  printf("My terminal is %s.\n", term);
  tgetent(bp, term);
  height = tgetnum ("li");
  width = tgetnum ("co");
  printf("H : %d\nL : %d\n", height, width);
  free(bp);
  return (0);
}

Do not forget to use the -lncurses library when you compile. Note that you can use the -ltermcap library as well:

cc main.c -lncurses

and

./a.out

cool

Comments

Comment: 

> The tgetent() function is a Linux system call function

tgetent is not part of linux, and is not a system call.

Also, your bp = malloc(sizeof(*bp)); pointlessly allocates just one byte, whereas the biggest termcap entry today seems to need 3208 bytes, so unless you are using ncurses' terminfo emulation layer which ignorsd the buffer pointer completely, tgetent() wil write all over the following memory, causing a core dump if you are lucky. Your example above craps all over the memory and exits, so you don't detect the memory corruption.

If you can detect that you are using GNU termcap, you can pass NULL as the buffer pointer, and tgetent will allcoate its own internal buffer of the right size. If you can detect that you'r using curses' termcap emulation layer, the buffer you pass is ignored anyway, so your bad code will appear to work...

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.