[英]c++ Redirect function output to compiled program input and viceversa
我有一個已編譯程序,該程序從std :: cin接收一些編碼數據,對其進行處理並在std :: cout中輸出編碼數據。 可執行程序代碼如下所示:
// 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;
}
現在,我想編寫一個程序來對其進行測試。 我有一個對數據進行編碼並將其發送到std :: cout的函數,以及另一個從std :: cin接收數據並對其進行解碼的函數(由於這是測試的一部分,因此我需要使用這些函數)。 這些功能如下所示:
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);
}
所以我想要一個使用encode_and_send來執行程序的程序,並使用receive_and_decode來捕獲可執行程序的輸出的程序:
我的測試程序如下所示:
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;
}
謝謝。
您可以創建一個臨時FIFO和使用它,管道發送std::cout
的的Main_Program
到std::cin
的Test_Program
, 反之亦然 ,這樣的事情在bash
:
mkfifo fifo # create a local fifo
Main_Program < fifo | Test_Program > fifo
rm fifo # don't need it once your finished
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.