C language. Read from stdout

前端 未结 4 1868
抹茶落季
抹茶落季 2021-01-03 01:30

I have some troubles with a library function. I have to write some C code that uses a library function which prints on the screen its internal steps. I am not interested to

相关标签:
4条回答
  • 2021-01-03 01:43

    An expanded version of the previous answer, without using files, and capturing stdout in a pipe, instead:

    #include <stdio.h>
    #include <unistd.h>
    
    main()
    {
       int  stdout_bk; //is fd for stdout backup
    
       printf("this is before redirection\n");
       stdout_bk = dup(fileno(stdout));
    
       int pipefd[2];
       pipe2(pipefd, 0); // O_NONBLOCK);
    
       // What used to be stdout will now go to the pipe.
       dup2(pipefd[1], fileno(stdout));
    
       printf("this is printed much later!\n");
       fflush(stdout);//flushall();
       write(pipefd[1], "good-bye", 9); // null-terminated string!
       close(pipefd[1]);
    
       dup2(stdout_bk, fileno(stdout));//restore
       printf("this is now\n");
    
       char buf[101];
       read(pipefd[0], buf, 100); 
       printf("got this from the pipe >>>%s<<<\n", buf);
    }
    

    Generates the following output:

    this is before redirection
    this is now
    got this from the pipe >>>this is printed much later!
    good-bye<<<
    
    0 讨论(0)
  • 2021-01-03 01:45

    I'm assuming you meant the standard input. Another possible function is gets, use man gets to understand how it works (pretty simple). Please show your code and explain where you failed for a better answer.

    0 讨论(0)
  • 2021-01-03 01:49

    You should be able to open a pipe, dup the write end into stdout and then read from the read-end of the pipe, something like the following, with error checking:

    int fds[2];
    pipe(fds);
    dup2(fds[1], stdout);
    read(fds[0], buf, buf_sz);
    
    0 讨论(0)
  • 2021-01-03 02:02
        FILE *fp;
        int  stdout_bk;//is fd for stdout backup
    
        stdout_bk = dup(fileno(stdout));
        fp=fopen("temp.txt","w");//file out, after read from file
        dup2(fileno(fp), fileno(stdout));
        /* ... */
        fflush(stdout);//flushall();
        fclose(fp);
    
        dup2(stdout_bk, fileno(stdout));//restore
    
    0 讨论(0)
提交回复
热议问题