How to redirect data to stdin in one executable file?

I use cxxtest as a test environment for my C ++ classes and would like to figure out a way to simulate sending data to classes that would normally expect to receive it from standard input. I have several different files that I would like to send to classes during different tests, so redirecting from the command line to the test suite executable is not an option.

Basically, I would like to find a way to override or redirect the 'stdin' descriptor to another value that I create inside my program, and then use fwrite () from these tests so that the corresponding fread () inside the class will extract data from the program, not from the actual standard I / O handles associated with the executable.

Is it possible? Bonus points for a platform-independent solution, but at least I need it to work with Visual Studio 9 under Windows.

+4
source share
5 answers

An appropriate method is to rewrite your classes so that they are validated. They should take a descriptor, stream or file from which they should read data as a parameter - in a test environment you can make fun of a stream or specify the path to a file containing test data.

+10
source

You should be able to use freopen () to point stdin to an arbitrary file.

+3
source

rdbuf does exactly what you want. You can open the file for reading and replacing cin rdbuf with one of the file. (see link for an example using cout).

On a unix-like OS, you can close the file descriptor 0 (stdin) and open another file. It will have the lowest descriptor available, which in this case is 0. Or use one of the posix calls that do just that. I am not sure, but it can also work on Windows.

+3
source

I think you want your classes to use direct stream instead of std::cin directly. You will either want to pass the input stream to the classes, or install it on them using some method. For exmaple, you can use stringstream to enter test input:

 std::istringstream iss("1.0 2 3.1415"); some_class.parse_nums(iss, one, two, pi); 
+2
source

We can redirect cin so that it reads data from a file. Here is an example:

 #include <iostream> #include <fstream> #include <string> int main() { std::ifstream inputFile("Main.cpp"); std::streambuf *inbuf = std::cin.rdbuf(inputFile.rdbuf()); string str; // print the content of the file without 'space' characters while(std::cin >> str) { std::cout << str; } // restore the initial buffer std::cin.rdbuf(inbuf); } 
+2
source

Source: https://habr.com/ru/post/1277247/


All Articles