Created
September 28, 2022 00:13
-
-
Save guychouk/a941a8e4a2c15d7c3f0c52f6e6fa3082 to your computer and use it in GitHub Desktop.
Ncurses and popen example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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