将输入发送到C程序并打印它们

问题描述 投票:2回答:2

[试图编写一个接受输入文件的脚本,并在程序要求输入(scanf)时将其一一发送给C程序。我希望我的脚本在将每个输入发送到程序之前先将其打印出来。C程序的整个输出(包括我提供的输入)应打印到文件中。

寻找解决方案而不更改我的C代码。

例如:

我的C程序:test.c

#include <stdio.h>

int main()
{
    char a[50];
    int b;
    printf("Enter your name:\n");
    scanf("%s",a);
    printf("HELLO: %s\n\n", a);
    printf("Enter your age:\n");
    scanf("%d",&b);
    printf("Your age is: %d\n\n", b);
    return 0;
}

我的脚本:myscript.sh

#!/bin/bash
gcc test.c -o mytest
cat input | ./mytest >> outputfile

我也尝试过

#!/bin/bash
gcc test.c -o mytest
./mytest < input > outputfile

我的输入文件:输入

Itzik
25

我的输出文件:outputfile

Enter your name:
HELLO: Itzik

Enter your age:
Your age is: 25

所需的outPutFile:

Enter your name:
Itzik
HELLO: Itzik

Enter your age:
25
Your age is: 25

非常感谢!

c bash input scanf
2个回答
2
投票

哦,我的..这会有点丑。

您可以在后台启动程序,从管道中读取程序,然后劫持该管道并对其进行写入,但仅在程序等待输入时才可以。在写入管道之前,先写入标准输出。

# Launch program in background
#
# The tail command hangs forever and does not produce output, thus
# prog will wait.
tail -f /dev/null | ./prog &

# Capture the PIDs of the two processes
PROGPID=$!
TAILPID=$(jobs -p %+)

# Hijack the write end of the pipe (standard out of the tail command).
# Afterwards, the tail command can be killed.
exec 3>/proc/$TAILPID/fd/1
kill $TAILPID

# Now read line by line from our own standard input
while IFS= read -r line
do
    # Check the state of prog ... we wait while it is Running.  More
    # complex programs than prog might enter other states which you
    # need to take care of!
    state=$(ps --no-headers -wwo stat -p $PROGPID)
    while [[ "x$state" == xR* ]]
    do
        sleep 0.01
        state=$(ps --no-headers -wwo stat -p $PROGPID)
    done
    # Now prog is waiting for input. Display our line, and then send
    # it to prog.
    echo $line
    echo $line >&3
done

# Close the pipe
exec 3>&-

我已将上面的源代码编译为名为prog的可执行文件,并将上述代码保存到pibs.sh中。结果:

$ bash pibs.sh < input 
Enter your name:
Daniel
HELLO: Daniel

Enter your age:
29
Your age is: 29


1
投票

如果不编写一个程序来分析test.c的输出并知道什么是输入提示,什么不是,那么您真正要问的是不可能的。

取决于程序的复杂程度,chat程序(请参阅man chat)或GNU期望的程序可能会有些运气。

您最好的选择是,如“ BobRun”所说,修改您的程序。无论您不想修改多少程序,都该将您可能遍历代码的所有scanf()放在适当的输入函数之后,如下所示:

int input_int(const char *prompt)
{
   printf ("%s:\n", prompt)
   int i = 0;
   scanf("%d", &i);

   /* Eat rest of line */
   int ch;
   do 
     ch = fgetc(stdin);
   while (ch != '\n' && ch != EOF)

   return i;
}

现在,添加错误检查和输入回显变得微不足道。而且您的程序可能会变得更易于阅读

摆脱该漏洞/安全漏洞scanf("%s", ...)也将很容易。

[如果您认为这是一项艰巨的工作,那就把它吸干吧。您确实应该从一开始就做起。而且,如果您再延迟工作,那很快就会成为卑鄙的。

© www.soinside.com 2019 - 2024. All rights reserved.