开发者

how to read output of system('ls')?

开发者 https://www.devze.com 2023-01-06 17:36 出处:网络
I am doing some file IO with c code. I have a particular pattern in my file. I can verify this by a shell command cat abc.txt | grep abc | wc -l. When I execute the same command using System(), it giv

I am doing some file IO with c code. I have a particular pattern in my file. I can verify this by a shell command cat abc.txt | grep abc | wc -l. When I execute the same command using System(), it give proper output, but I have no clue how can I get its ou开发者_如何转开发tput into a variable and compare it in my c code itself.

I tried looking into man pages which suggest using WEXITSTATUS(). This actually returns the status of execution and not output.

F1 !!


You don't want system(3) for that. Try popen(3) and friends.


What grep and wc are doing are reading the STDIN file handle as part of the pipe | operator.


You can try:

...
pid_t pid = fork();
if(pid == 0){
    int fd = open("output", O_RDWR | O_CREATE);
    close(1);
    (void) dup(fd);  // this will return 1
    system(your_cmd);
    // read output from fd
    // close fd
    // exit
}
else{
...

This will redirect output from command executed by system() to your "output" file.

0

精彩评论

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