gpt4 book ai didi

c - 读取字符串中的 gcc 输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:18 25 4
gpt4 key购买 nike

如果我们通过 system() 函数执行 gcc 来编译源文件,我怎样才能将 gcc 输出捕获到一个字符串中?


我尝试使用 popen,只要它读取类似 "PAUSE" 的内容,它就可以工作,但不能使用 gcc,因为它运行一个新的子进程。

最佳答案

方法有很多。

简单的方法:将输出重定向到临时文件并将临时文件读入字符串。

您可以使用管道。在子进程中,将输出重定向到管道,并从管道的另一端读入一个字符串。参见man pipe

//In the parent process
int fd[2]
pipes(fd);

//Use fork+execv instead of system to launch child process.
if (fork()==0) {
//Redirect output to fd[0]
dup2(fileno(fd[0]), STDOUT_FILENO);
dup2(fileno(fd[0]), STDERR_FILENO);
//Use execv function to load gcc with arguments.

} else {
//read from the other end fd[1]
}

请参阅 http://ubuntuforums.org/archive/index.php/t-1627614.html 处的主题.

另见 In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?

对于 Windows,此链接可能对您有所帮助。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspxFlow 几乎与 Linux 相同。语法和原语可能不同。在这里,想法是使用 Pipe 并将进程输出文件重定向到您的管道文件。

关于c - 读取字符串中的 gcc 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29224548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com