是否可以将文件重定向到控制台程序,就像用户键入内容一样?

发布于 2024-12-14 06:30:59 字数 538 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-12-21 06:30:59

您的文件内容必须是这样的:

12

没有 \n

我尝试了您的程序并且它有效!

echo '12' | ./prog

Your file content must be this:

12

Without \n

I tried your program and it works!

echo '12' | ./prog
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文