Skip to content

Instantly share code, notes, and snippets.

@guychouk
Created September 28, 2022 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guychouk/a941a8e4a2c15d7c3f0c52f6e6fa3082 to your computer and use it in GitHub Desktop.
Save guychouk/a941a8e4a2c15d7c3f0c52f6e6fa3082 to your computer and use it in GitHub Desktop.
Ncurses and popen example
/* install ncurses and compile in the following manner: */
/* gcc -std=c99 -Wpedantic -Wall -lncurses main.c */
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int height, width, ch;
FILE *fp;
WINDOW *win;
char cmd[100];
char mesg[] = "Enter command: ";
/* init ncurses */
initscr();
/* disables line buffering */
cbreak();
/* disables key echoing */
noecho();
/* read function keys (F1, F2...) */
keypad(stdscr, TRUE);
/* get height and width of screen */
getmaxyx(stdscr, height, width);
/* create a new window */
win = newwin(height - 2, width - 2, 1, 1);
scrollok(win, TRUE);
refresh();
box(win, 0, 0);
wrefresh(win);
while((ch = getch()) != 'q')
{
switch(ch)
{
case KEY_RESIZE:
wclear(win);
clear();
refresh();
box(win, 0, 0);
wrefresh(win);
break;
case 'e':
echo();
mvwprintw(win, 1, 2, "%s", mesg);
wrefresh(win);
wgetstr(win, cmd);
noecho();
break;
case 'r':
if ((fp = popen(cmd, "r")) != 0) {
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), fp) != 0) {
wprintw(win, "%s", buffer);
wrefresh(win);
}
pclose(fp);
}
}
}
endwin();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment