6

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.

1
  • As a completion for Li-chih Wu's answer. The dup function does not take 2 arguments anymore, it has already been renamed to dup2 by the time of writing this answer Commented Dec 24, 2020 at 1:19

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

That is a great advice. Highly appreciated, and I will be sure to try that in future implementations. Thank you.
1
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

1 Comment

Whether or not this is what the OP's question was about, this is extremely helpful to me, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.