如何从bash为C程序提供输入?

bla*_*all 17 c bash

我一直在阅读关于bash脚本和程序测试的文章,但我仍然无法使这段代码工作.

基本上它是一个简单的程序,要求用户提供north east southwest.我启动程序然后它立即要求输入.我只是不能让bash脚本给它任何输入.我试过用echoexpect.

任何帮助表示赞赏.

以下是用于获取玩家输入的函数:

int process_input(Map *game)
{
    printf("\n> ");

    char ch = getchar();
    char a = getchar(); //eat enter

    int damage = rand() % 4;

    switch(ch) {

        case -1:
            printf("you suck\n");
            return 0;
            break;
        case 'n':
            game->proto.move(game, NORTH);
            break;
        case 's':
            game->_(move)(game, SOUTH);
            break;
        case 'e':
            game->_(move)(game, EAST);
            break;
        case 'w':
            game->_(move)(game, WEST);
            break;
        case 'a':
            game->_(attack)(game, damage);
            break;
        case 'l':
                    printf("You can go:\n");
                    if(game->location->north) printf("NORTH\n");
                    if(game->location->south) printf("SOUTH\n");
                    if(game->location->east) printf("EAST\n");
                if(game->location->west) printf("WEST\n");
                    break;
        default:
            printf("Whats next?", ch);
        }
        return 1;
}
Run Code Online (Sandbox Code Playgroud)

以下是bash脚本的尝试:

   #!/bin/bash
    /Desktop/c
    ./ex17 echo 'w'
Run Code Online (Sandbox Code Playgroud)

Mar*_*eed 27

您可以使用以下任何一种机制从bash向程序提供输入.

对于单行输入,您可以使用'here-string':

./ex17 <<<'w'
Run Code Online (Sandbox Code Playgroud)

对于多行,您可以使用"here-document":

./ex17 <<'EOF'
w
second line of input
more input
EOF
Run Code Online (Sandbox Code Playgroud)

或者您可以将这些行移出脚本并转移到单独的文件中:

./ex17 <filename    
Run Code Online (Sandbox Code Playgroud)

更一般地说,您可以运行一个命令,为您的程序生成所需的输入,并使用"管道"将它们连接在一起.例如,上面也可以写成:

cat filename | ./ex17
Run Code Online (Sandbox Code Playgroud)

这更通用,因为您可以替换cat任何类型的程序,它可以执行各种计算以确定它输出的内容而不是仅仅转储静态文件的内容.

但是你不能轻易做到的就是驱动器输入,读取输出,并决定将什么作为下一个输入发送.为此,你应该看看期望.期望脚本看起来像这样:

echo w | ./ex17
Run Code Online (Sandbox Code Playgroud)


Ahm*_*sud 5

试试这个:首先:

 echo w | ./ex17 
Run Code Online (Sandbox Code Playgroud)

这会将w发送到示例并输出移动。这称为管道;它实际上将echo的stdout连接到ex17的stdin