简体   繁体   English

如何使用 C++ 在另一个程序中读取源代码的输出

[英]How to read output of source code in another program with C++

I think this is really hard to explain what I want.我认为这真的很难解释我想要什么。 But, let me try.但是,让我试试。 (I am trying to build a program for scoring student's programming homework) (我正在尝试构建一个程序来为学生的编程作业评分

There are a lot of simple source codes in C++. C++中有很多简单的源代码。 (Please think there are more than 100 code files ) (请认为有 100 多个代码文件

// C:\homework1\studentA.cpp
int main()
{
    cout << "The answer is 456" << endl;
}

And This is question.这是问题。 As you can see, there are tons of code files and I cannot compile it and check it whether right or wrong one by one.如您所见,代码文件数以千计,我无法对其进行编译和检查是否正确。 So, I need to make scoring program for convenience.所以,为了方便,我需要制作评分程序。

How can I read the standard output (The answer is 456) in another program ?如何在另一个程序中读取标准输出(答案是 456)? Is there any function for 'compiling source code' and 'save standard output' ?是否有“编译源代码”和“保存标准输出”的功能?

I would use a bash script for this instead of C++.我会为此使用 bash 脚本而不是 C++。 Something along the lines of:类似的东西:

g++ $filename
./a.out > student_answer.txt
diff -q student_answer.txt expected_answer.txt

Then, $?那么, $? would tell you whether the answer was correct.会告诉你答案是否正确。

How can I read the standard output (The answer is 456) in another program?如何在另一个程序中读取标准输出(答案是 456)?

You cannot do that without help from your operating system .如果没有操作系统的帮助,您将无法做到这一点。 Because you don't have (in general, according to the C++17 standard ) some "other program" running (read about processes ).因为你没有(通常,根据C++17 标准)一些“其他程序”正在运行(阅读进程)。 When you have one, please thank your OS.当你有一个时,请感谢你的操作系统。 Read some textbook about operating systems .阅读一些关于操作系统的教科书

However, on Linux, you could just use popen(3) (or fork(2) , execve(2) , pipe(7) so pipe(2) , dup2(2) , waitpid(2) ) and on operating systems for which Qt has been ported (that includes Windows, but read about the WinAPI ), you could use QProcess .但是,在 Linux 上,您可以只使用popen(3) (或fork(2)execve(2)pipe(7) so pipe(2)dup2(2)waitpid(2) )和操作系统上Qt已被移植(包括 Windows,但阅读有关WinAPI 的内容),您可以使用QProcess

If you are paranoid, consider using setuid and/or chroot techniques (perhaps with LXC ) on Linux to increase the security of your tool.如果您有疑虑,请考虑在 Linux 上使用setuid和/或chroot技术(可能使用LXC )来提高工具的安全性。

Look also inside the POCO framework library.另请查看POCO框架库内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM