Home > Back-end >  Redirect output to file, then redirect to console in Linux
Redirect output to file, then redirect to console in Linux

Time:10-13

I have code. It redirects output to file. How I can return output to console? I tried to do it, but it doesn't work.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
   int save1 = dup(1);
   int fd = open("my_test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
   if (fd == -1) {}
   dup2(fd, 1);
   printf("to file");
   close(fd);

   dup2(save1, 1);
   close(save1);
   printf("to console");

}

CodePudding user response:

You are suffering from buffering.

Simply adding calls to fflush( stdout ) does the trick.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(void) {
   int saved1 = dup(1);
   int fd = open("my_test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
   dup2(fd, 1);
   close(fd);

   printf("to file\n");

   fflush(stdout);
   dup2(saved1, 1);
   close(saved1);

   printf("to console\n");
}
$ gcc -Wall -Wextra -pedantic a.c -o a && ./a
to console

$ cat my_test.txt
to file
  • Related