11

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 its return value, but only to printed steps. So, I think I have to read from standard output and to copy read strings in a buffer. I already tried fscanf and dup2 but I can't read from standard output. Please, could anyone help me?

1
  • 1
    Show the code you tried, please! If you made a pipe and used dup2 correctly you should have been able to do what you're trying.
    – Carl Norum
    Jun 12, 2013 at 17:33

4 Answers 4

17

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<<<
1
8

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);
1
  • Ok, I fixed it with a non pure solution. I used C++. Jun 12, 2013 at 17:41
2
    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

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.

2
  • 2
    No, OP is talking about stdout. He has a library function that writes to stdout, and he wants to intercept that output.
    – Carl Norum
    Jun 12, 2013 at 17:35
  • ok, but there is still a thing I don't undestand. Why if I want read the written file, i can't? I cannot post the code 'cause 8 hours have to pass :S Jun 12, 2013 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.