Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top