如何在 C 中创建一个程序来编译和运行另一个 c 程序并将输出保存在 txt 文件中?

How to create a program in C that compiles and runs another c program and saves the output in a txt file?

我想用 C 创建一个程序,以便它编译另一个 c 程序并将输出保存在文本文件中。例如,我希望使用 C 程序将 "input.c" 文件的输出存储在名为 "output.txt" 的文本文件中。请帮忙。

我选择这个项目是因为在 Turbo C++ 中复制整个输出屏幕通常变得很困难,有时 turbo c 不显示整个输出而只复制当前输出屏幕,留下以前的输出。

有可能。您要么 运行 一个 shell 编译的命令,然后 运行s 您的子程序(man 3 system,简单),或者您使用更高级的技术,例如即时编译(http://blog.coldflake.com/posts/On-the-fly-C++/ or https://bellard.org/tcc/ 如果您是 C 程序员)

C11 标准(读取 n1570) does not define how to run a compiler. In many cases (think about cross-compiling for some Arduino 目标)您将无法 运行 目标机器上的编译器(可能是 "too small")。

顺便说一句,您可以将您的代码编译成一些可执行文件,从您的系统中删除每个编译器,然后 运行 该可执行文件(在您的系统没有任何编译器的情况下)......

C11 标准在 §7.22.4.8 中含糊地说了一个 system 函数。

在某些实现中,system 函数能够通过某些 未指定的 命令启动 其他 程序(在进程中)处理器。但是不能保证您将能够启动 编译器 (例如,您可以 运行 您的可执行文件在 Windows 计算机上没有任何编译器) .

(实际上,您的计算机可能实际上有一些命令行 C 编译器,但您需要知道是哪一个以及如何调用它)

, you could use system(3) (which uses /bin/sh -c), but also fork(2) & execve(2) -and other functions, e.g. popen(3)- 启动其他程序。

在 Linux 上,您通常有一些 命令行 编译器,通常 GCCgcc(甚至 cc ).你可以 运行 它(例如使用 system)。

我喜欢在我的 Linux 系统上使用以下技巧:生成一些包含 C 代码的 临时 文件,例如/tmp/temporaryc.c,然后将该临时文件编译成一些临时文件 plugin /tmp/temporaryplugin.so by using system with a command (in a string built at runtime) like gcc -Wall -O -fPIC -shared /tmp/temporaryc.c -o /tmp/temporaryplugin.so, and at last dynamically load that plugin using dlopen(3)

另请查看 JIT-compilation libraries like libgccjit

顺便说一句,您应该考虑放弃 Turbo C(它是用于 C 或 C++ 过时变体的过时编译器)并在您的 PC 上切换到 Linux。

您想查看名为 system() 和 POSIX popen().

的标准 C 函数

在带有 C 编译器的 POSIXly 系统上,编译一个简单的 C 程序将是

system("cc -o input input.c");

然后运行它并捕获输出,

FILE *fp_in = popen("./input", "r"); /* to read */
FILE *fp_out = fopen("output.txt", "w"); /* to write */

然后从fp_in读取并写入fp_out。这是基本的想法。我已将细节留给您去弄清楚,这样您就可以深入了解深层的 C 秘密:-) 不要忘记所有库函数的错误处理。

PS:如果系统的 shell 支持重定向,您甚至可以将 popen/fopen 组合简化为单个 system("./input > output.txt");

PPS:如果 PS 有效,您不妨将所有内容组合成 system("cc -o input input.c && ./input > output.txt"); 我相信您知道如何将其包装在 main() 中。