I know you can give input to a C program in linux like this
me $ printf "some input" | ./someProgram
I want to do the same thing using input from a file, like this
me $ myProgram < myFile.txt
myProgram has two gets statements that I want to fill w/printfs as input.
printf("...."); fflush(stdout);
gets(var1);
printf("...."); fflush(stdout);
gets(var2);
The program behaves as expected when I fill the vars from an input file like this
"12345" //expect to fill var1 w/ 12345 and it does
"12345" //expect to fill var2 w/ 12345 and it does
But the program does not behave as expected when my input file looks like this
printf "12345" //expect to fill var1 w/ 12345 but it does not
printf "12345" //expect to fill var2 w/ 12345 but it does not
Clearly, C is not interpreting the print command in the same was as if I gave the command as input and then piped it into the program.
What's going on? What do I fix? How can I give printf input from a file?
C isn't interpreting any commands at all. When you use ... < file
to redirect stdin
, the contents of that file become the input to your program - verbatim. So if the file contains
"12345"
"abc"
, then var1
will be "12345"
(not 12345
) and var2
will be "abc"
(not abc
). Similarly, if the file contains
printf "12345"
printf "12345"
, then var1
will be printf "12345"
and var2
will be printf "12345"
.
As I see it, you have two choices: Either you put
12345
12345
in the file and use ./someProgram < myFile.txt
, or you put
printf "12345\n"
printf "12345\n"
in the file and use sh myFile.txt | ./someProgram
sh myFile.txt | ./someProgram
(executing the contents of myFile.txt as a shell script).
You are missing the trailing newline.
printf "12345\\n"
should work well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.