且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将系统的输出(char *命令)加载到变量,C ++

更新时间:2023-12-02 20:08:10

我建议这样做:

FILE *fp = popen("fortune","r");
char line[200];
while(!feof(fp)) {
fgets(line,200,fp);
// process here
}
pclose(fp);

如果它确实对性能至关重要,那么***使用fork()和管道为该孩子的stdin/stdout创建一个孩子进程写入或读取的过程.可以在此处找到一个示例(http://www.microhowto.info/howto/如果您已接受测试,则为capture_the_output_of_a_child_process_in_c.html#idp21888 ).但是popen方法可能是您所用的最简单直接的方法.

If it's really performance critical it's probably better to create a child process using fork() and pipes for stdin/stdout of that child process to write or read from. An example of this could be found here (http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp21888) if you're intested. But the popen method is probably the most simple and straightforward one in your case.