[英]how do i feed printf as input to a C program using a file?
I know you can give input to a C program in linux like this 我知道你可以像这样给linux中的C程序输入
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. myProgram有两个gets语句,我想填充w / printfs作为输入。
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. 显然,C不是在解释打印命令,就好像我将命令作为输入,然后将其传送到程序中。
What's going on? 这是怎么回事? What do I fix? 我该怎么办? How can I give printf input from a file? 如何从文件中输入printf?
C isn't interpreting any commands at all. C根本不解释任何命令。 When you use ... < file
to redirect stdin
, the contents of that file become the input to your program - verbatim. 当您使用... < file
重定向stdin
,该文件的内容将成为程序的输入 - 逐字。 So if the file contains 所以如果文件包含
"12345"
"abc"
, then var1
will be "12345"
(not 12345
) and var2
will be "abc"
(not abc
). ,则var1
将为"12345"
(不是12345
), var2
将为"abc"
(不是abc
)。 Similarly, if the file contains 同样,如果文件包含
printf "12345"
printf "12345"
, then var1
will be printf "12345"
and var2
will be printf "12345"
. ,那么var1
将是printf "12345"
, var2
将是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 在文件中并使用./someProgram < myFile.txt
,或者你放
printf "12345\n"
printf "12345\n"
in the file and use sh myFile.txt | ./someProgram
在文件中使用sh myFile.txt | ./someProgram
sh myFile.txt | ./someProgram
(executing the contents of myFile.txt as a shell script). sh myFile.txt | ./someProgram
(将sh myFile.txt | ./someProgram
的内容作为shell脚本执行)。
You are missing the trailing newline. 您缺少尾随换行符。
printf "12345\\n"
should work well. printf "12345\\n"
应该运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.