是否可以将文件重定向到控制台程序,就像用户键入内容一样?
我有一个 C 程序,它使用 scanf 读取数字,然后打印该数字。我想通过重定向文件来模拟击键,这样我就可以制作一个应该进行黑盒测试的 bash 脚本。
这是我的程序(prog):
int main(){
int a;
printf("Write a number: ", a);
fflush(stdout);
scanf("%d", &a);
printf("\nYou entered: %d\n", a);
return 0;
}
然后我有一个包含以下内容的文件(infile):
12\n
是否可以以某种方式将文件重定向为程序的输入来模拟用户输入?
打字时
./prog < infile
我得到
Write a number:
You entered: 0
I have a C program which uses a scanf to read a number and then prints the number. I want somehow to simulate the keystrokes by redirecting a file so I can make a bash script that is supposed to do black-box-testing.
This is my program(prog):
int main(){
int a;
printf("Write a number: ", a);
fflush(stdout);
scanf("%d", &a);
printf("\nYou entered: %d\n", a);
return 0;
}
I then have a file(infile) with this content:
12\n
Is it possible somehow to redirect the file as input to the program to simulate user input?
When typing
./prog < infile
I get
Write a number:
You entered: 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的文件内容必须是这样的:
没有 \n
我尝试了您的程序并且它有效!
Your file content must be this:
Without \n
I tried your program and it works!