2
votes

I have a compiled program that receives some encoded data from std::cin, processes it and outputs encoded data in std::cout. The executable program code looks something like this:

// Main_Program.cpp
// Compiled program that processes data.
int main(int argc, char* argv[]) {
    std::string data_in;
    std::string data_out;

    std::cin >> data_in;
    process_data(data_in, data_out);
    std::cout << data_out;

    return 0;
}

Now I want to make a program to test it. I have a function that encodes data and sends it to std::cout and another function that receives data from std::cin and decodes it (I need to use these functions since it's part of the testing). These functions look like:

void encode_and_send(std::string non_encoded_data) {
    std::string encoded_data;
    encode_data(non_encoded_data, encoded_data);
    std::cout << encoded_data;
}

void receive_and_decode(std::string &non_encoded_data) {
    std::string encoded_data;
    std::cin >> encoded_data;
    decode_data(encoded_data, non_encoded_data);  
}

So I want a program that uses encode_and_send to feet the executable program, and uses receive_and_decode to capture the output of the executable program:

My test program looks like:

int main(int argc, char* argv[]) {
    std::string testdata = "NonEncodedDataToBeProcessed";
    std::string received_data;

    // How can I use this three calls to correctly handle input and output data? 
    // One option would be to redirect cout and cin to temp files and read them 
    // when calling the ./Main_Program, but is there a way to avoid files and 
    // directily redirect or pipe the inputs and outputs? 

    // encode_and_send(testdata);
    // system("./Main_Program");
    // receive_and_decode(received_data);

    // Here I can check that received_data is correct

    return 0;
}

Thanks.

1
You can use a pipe to communicate with other processes standard input output handles.πάντα ῥεῖ

1 Answers

0
votes

You can create a temporary fifo and use it and a pipe to send the std::cout of the Main_Program to the std::cin of Test_Program and vice versa, something like this in bash:

mkfifo fifo # create a local fifo
Main_Program < fifo | Test_Program > fifo
rm fifo  # don't need it once your finished