Search code examples
cterminalncursescurses

ncurses and C- Display output of 'df' command in ncurses window


I am relatively new to ncurses and was just wondering what would be the simple way to display the output of a command executed in terminal/the command line in the ncurses TUI that I am starting. i.e something like this psuedocode (which I know doesn't work, just to get the point accross :) The goal is to present a menu screen displaying various system information like available memory, network info, etc:

#include <ncurses.h>
#include <stdlib.h>
#include <stdio.h>


int main(){

initscr();
cbreak();
char command[] = "df";
printw(system(command));
}

Solution

  • You can do this by opening a pipe to the command (the example should use "df", by the way). Something like this:

    #include <ncurses.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    int
    main(void)
    {
        FILE *pp;
    
        initscr();
        cbreak();
        if ((pp = popen("df", "r")) != 0) {
            char buffer[BUFSIZ];
            while (fgets(buffer, sizeof(buffer), pp) != 0) {
                addstr(buffer);
            }
            pclose(pp);
        }
        getch();
        return EXIT_SUCCESS;
    }