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

ItzikF

尝试编写一个接受输入文件的脚本,并在程序要求输入时将它们一一发送给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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用sh脚本将输入发送到程序

如何将python列表发送到C ++应用程序等待输入?

如何使用Shell脚本将输入发送到C程序

使用 txt 文件将输入发送到我的 C 程序

将输入从函数发送到变量?

从Java应用程序将条形码发送到Zebra打印机

后台打印程序概念/ API和渠道:将通过JobHTTP的传递作业发送到队列

将输入从Python程序发送到命令行提示符

将输入值发送到React中的点击处理程序

如何从PowerShell将输入发送到控制台应用程序

将输入发送到Node Webkit中的控制台应用程序

在Windows中以编程方式将键盘输入发送到图形应用程序(游戏)

如何将参数作为输入发送到mysql程序中?

无法打印从用户空间C应用程序发送到linux内核模块的消息

我可以直接将打印作业从python程序发送到CUPS打印服务器的IP地址吗?

我的应用程序将打印文件发送到另一台网络打印机

C#将文件(pdf,html或rtf)发送到打印机

如何通过USB使用C#将原始ZPL发送到zebra打印机

将数据从节点发送到python并打印

将纯文本发送到默认打印机

如何打印出将发送到oracle的sql查询

将原始命令发送到连接的打印机

将 div 发送到单独的页面进行打印

如何以编程方式从C#Windows Forms应用程序将openoffice writer odt文件发送到打印机

在C中使用getchar()将输入发送到char数组

C#通过命令提示符将输入发送到单独的进程

C#将按键输入发送到Minecraft以移动播放器

将数据从Python程序发送到Java程序

如何使用 StringIO() 对象作为程序的标准输入将字符串发送到输入语句,