Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language. Read from stdout

Tags:

c

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?

like image 895
user2479368 Avatar asked Jun 12 '13 17:06

user2479368


People also ask

How do you read from stdin in c?

The built-in function in c programming is getline() which is used for reading the lines from the stdin. But we can also use other functions like getchar() and scanf() for reading the lines.

What is stdin and stdout in c?

//Under c windows os. "stdin" stands for standard input. "stdout" stands for standard output. "stderr" stands for standard error. It's Function prototypes are defined in "stdio.

What is stdin in c language?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java.

What is stdout in c?

stdout stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin and stderr .


1 Answers

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<<<
like image 50
Linas Avatar answered Sep 30 '22 20:09

Linas