Redirect standard output to c and then reset standard output

I am trying to use C redirects to redirect input to a single file, and then set the standard output back to print to the screen. Can someone tell me what is wrong with this code?

#include <stdio.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char** argv) { //create file "test" if it doesn't exist and open for writing setting permissions to 777 int file = open("test", O_CREAT | O_WRONLY, 0777); //create another file handle for output int current_out = dup(1); printf("this will be printed to the screen\n"); if(dup2(file, 1) < 0) { fprintf(stderr, "couldn't redirect output\n"); return 1; } printf("this will be printed to the file\n"); if(dup2(current_out, file) < 0) { fprintf(stderr, "couldn't reset output\n"); return 1; } printf("and this will be printed to the screen again\n"); return 0; } 
+6
source share
3 answers

The second call to dup2 incorrect, replace with:

 if (dup2(current_out, 1) < 0) { 
+3
source

One thing you will need to do before this works at all is to call fflush(stdout); before switching the file descriptor stdout from under it. What is likely to happen is that the standard C library buffers your output without suspecting that you are moving around the file descriptors below it. The data you write with printf() is not actually sent to the base file descriptor until its buffer is full (or your program returns with main ).

Insert the call as follows:

  fflush(stdout); if(dup2(file, 1) < 0) { 

before both calls to dup2() .

+4
source

Just replace dup2(current_out, file) with dup2(current_out, 1) and everything will work better.

+1
source

Source: https://habr.com/ru/post/893438/


All Articles