user2479368
user2479368

Reputation: 121

C language. Read from stdout

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?

Upvotes: 12

Views: 25664

Answers (4)

Linas
Linas

Reputation: 782

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

Upvotes: 18

BLUEPIXY
BLUEPIXY

Reputation: 40145

    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

Upvotes: 2

Paul Rubel
Paul Rubel

Reputation: 27222

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);

Upvotes: 8

user2478971
user2478971

Reputation:

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.

Upvotes: 0

Related Questions