将标准输入和标准输出重定向到文件
我目前是C 入门课程的助教。 该课程是使用 Visual Studio 进行教学的,但是在评分时,我只使用一个简单的 Windows 批处理脚本来处理所有提交的作业,编译它们,在测试文件上运行它们,并将输出重定向到我可以打印的一系列文本文件拿出来,做好标记,然后交还给学生。 整个过程运行得很好,除了当我重定向 stdin 时,它不会像直接在控制台中输入相同的 stdin 时那样出现在重定向的 stdout 中。 因此,为控制台格式化的代码输出在重定向的输出中无法正确显示。 以下文件片段显示了此问题。 有谁知道一个简单的解决方案?
文件: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:\>
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?
File: example.c
#include <stdio.h>
int main()
{
int v;
printf("Enter a number: ");
scanf("%i", &v);
printf("You entered: %d\n", v);
return 0;
}
File: input.txt
42
Output (Console)
C:\>example.exe
Enter a number: 42
You entered: 42
C:\>
Output (Redirection)
C:\>example.exe < input.txt > output.txt
C:\>more output.txt
Enter a number: You entered: 42
C:\>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是预期的(正确的)行为。 输入永远不是标准输出的一部分。 如果您执行
example.exe > 如果盲目地输入 42,您应该预料到 42 在输出中也只出现一次。
我能想到的唯一解决方案是终端/shell 记录整个会话。 Windows 命令 shell 无法做到这一点。 不过,您可以编写自己的终端代理,它将标准输入输入学生的程序并读取输出本身,同时以组合方式写出两者。 在 POSIX 下创建另一个程序的执行并重定向该程序的标准输入/输出非常容易(由 Cygwin 提供),但我不知道普通的 DOS/Windows。
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.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.