开发者

How to use a terminal command's output in my program?

开发者 https://www.devze.com 2023-02-14 20:54 出处:网络
I want to parse the output of 开发者_JAVA技巧the command w for use in my program I know i can execute w using execlp but is there a way to get the output from w into my program directly? I\'m thinking

I want to parse the output of 开发者_JAVA技巧the command w for use in my program I know i can execute w using execlp but is there a way to get the output from w into my program directly? I'm thinking i could use a pipe or something, but I don't know very much about it or how pipes work in an execlp command.

Thanks for the help


Look at popen for a simple way to do that, although it has various weaknesses (calling out to the shell, for example). libslack also has a popen replacement (the coprocess functions); it is under the GPL.


Use popen(3):

#include <stdio.h>
main()
{
 char *command="w";
 FILE *fpipe = (FILE*)popen(command,"r")) );
 char line[256];
 while ( fgets( line, sizeof(line), fpipe))
 {
  printf("%s", line);
 }
 pclose(fpipe);
}


man popen

(some other random characters to get past lame filter)

0

精彩评论

暂无评论...
验证码 换一张
取 消