Milan
Milan

Reputation: 15849

C/C++ add input to stdin from the program?

Is that even possible ?

Lets say that the code has a lot of scanf lines. Instead of manually running and adding values by hand when debugging, is it possible to "feed" stdin with data so that when the scanf starts reading, it will read the inputted data without any need to interact with the terminal.

Upvotes: 6

Views: 7451

Answers (3)

Li-chih Wu
Li-chih Wu

Reputation: 1082

int fd[2];
pipe(fd);
close(0); // 0:stdin
dup(fd[0], 0); // make read pipe be stdin
close(fd[0]);
fd[0] = 0;

write(fd[1], "some text", 9); // write "some text" to stdin

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258128

To make your program a little more versatile, you might want to consider rewriting your program to use fscanf, fprintf, etc. so that it can already handle file IO as opposed to just console IO; then when you want to read from stdin or write to stdout, you would just do something along the lines of:

FILE *infile, *outfile;

if (use_console) {
    infile = stdin;
    outfile = stdout;
} else {
    infile = fopen("intest.txt", "r");
    outfile = fopen("output.txt", "w");
}
fscanf(infile, "%d", &x);
fprintf(outfile, "2*x is %d", 2*x);

Because how often do programs only handle stdin/stdout and not allow files? Especially if you end up using your program in shell scripts, it can be more explicit to specify input and outputs on the command line.

Upvotes: 5

RichieHindle
RichieHindle

Reputation: 281365

Put the test lines into a file, and run the program like this:

myprogram < mytestlines.txt

Better than hacking your program to somehow do that itself.

When you're debugging the code, you can set up the debugger to run it with that command line.

Upvotes: 14

Related Questions