将Stdin和Stdout重定向到文件 [英] Redirect Stdin and Stdout to File

查看:172
本文介绍了将Stdin和Stdout重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前是 C课程简介的助教.该课程使用Visual Studio进行授课,但在评分时,我仅使用一个简单的Windows批处理脚本来处理所有作业提交,编译,在测试文件上运行它们,并将输出重定向到我可以打印的一系列文本文件出来,标记出来,然后交还给学生.整个过程运行得非常好,除了以下事实:当我重定向标准输入时,它不会以与将相同标准输入直接输入到控制台中时相同的方式出现在重定向的标准输出中.因此,为控制台格式化的代码输出在重定向的输出中无法正确显示.以下文件片段显示了此问题.有谁知道一个简单的解决方案?

I'm currently the Teaching Assistant for an Introduction to C class. The class is being taught using Visual Studio, but when grading I just use a simple Windows batch script to process all the assignment submissions, compile them, run them on a test file, and redirect the output to a series of text files I can print out, mark up, and hand back to students. The whole process works very well, except for the fact that when I redirect stdin, it does not appear in the redirected stdout the same way it does when the same stdin is typed directly into the console. Because of this, the output of code formatted for the console does not display correctly in the redirected output. The following file snippets show this problem. Does anyone know of a simple solution?

文件:example.c

#include <stdio.h>

int main()
{
    int v;
    printf("Enter a number: ");
    scanf("%i", &v);
    printf("You entered: %d\n", v);
    return 0;
}

文件:input.txt

42

输出(控制台)

C:\>example.exe
Enter a number: 42
You entered: 42

C:\>

输出(重定向)

C:\>example.exe < input.txt > output.txt

C:\>more output.txt
Enter a number: You entered: 42

C:\>

推荐答案

这是预期的(正确的)行为.输入永远不会是stdout的一部分.如果您执行example.exe > output.txt并盲目键入42,则应该期望42在输出中也只显示一次.

This is expected (correct) behaviour. The input is never part of stdout. If you do example.exe > output.txt and blindly type in 42, you should expect that 42 also shows up only once in the output.

我能想到的唯一解决方案是终端/外壳记录整个会话. Windows命令外壳不具备此功能.不过,您可以编写自己的终端代理,它将标准输入输入学生的程序中并读取输出本身,同时以组合方式将两者写出.可以很容易地分叉另一个程序的执行,然后将其标准输入/输出重定向到POSIX下(由Cygwin提供给您),尽管我不了解纯DO​​S/Windows.

The only solution I could think of is that the terminal/shell records the session as a whole. Windows command shell is not capable of that. You could write your own terminal proxy though, which feeds stdin into the student's program and reads the output itself, while writing out both in a combined fashion. It is quite easy to fork for exection of another program and redirect that one's stdin/out under POSIX (provided to you by Cygwin), I don't know about plain DOS/Windows though.

这篇关于将Stdin和Stdout重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆