尝试编写一个接受输入文件的脚本,并在程序要求输入时将它们一一发送给C程序(scanf)。我希望我的脚本在将每个输入发送到程序之前先将其打印出来。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
非常感谢!
哦,我的..这会有点难看。
您可以在后台启动该程序,从管道中读取该程序,然后劫持该管道并对其进行写入,但前提是程序正在等待输入。在写入管道之前,先写入标准输出。
# 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句