Question

I am trying to get the output produced by a command entered through libexpect, I am not very skilled at the C style of doing things, and I'm not sure how to proceed.

The problem is that it seems while this a popular program for python users, I can only find a few basic examples of using libexpect in C/C++ and none seem to mention getting the output.

Example program:

// g++ t.cpp -lexpect -ltcl -o t
#include <iostream>
#include <tcl8.5/expect.h>

int main(){
    FILE *echo = exp_popen(const_cast<char *>("telnet google.com 80"));
    std::cout << char(fgetc(echo)) << std::endl;

    std::cout << std::string(80, '=') << std::endl;
    char c;
    do{
            c = fgetc(echo);
            std::cout << "'" << c << "'";
    }while(c != EOF);

    return 0;
}

While this partially works, it fails get the first character.

Was it helpful?

Solution

Actually, SO showed a link on the side right after I posted showing the correct answer, I guess I did not look hard enough:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tcl8.5/expect.h>
#include <errno.h>

int main()
{
    char str[512];
    FILE *f = exp_popen("ssh user@mybox ls -lR");
    if (f==NULL)
    {
        printf("Failed (%s)\n", strerror(errno));
        return 1;
    }
    while(fgets(str, sizeof(str)-1, f))
    {
        printf("%s", str);
    }
    return 0;
}

(Taken from How to read stdout from a FILE* created with libexpect in C++ on linux?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top