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

前端 未结 3 377
情深已故
情深已故 2021-01-16 12:56

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

3条回答
  •  不知归路
    2021-01-16 13:30

    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.

提交回复
热议问题