I have a doubt regarding file descriptors used in C language. I am trying to redirect standard output to a text file so that printf("") output goes in the file.
Using dup2,I have written following code snippet. The code works fine and I get 2 strings "sugar" and "spice" on screen output and "salt" is stored in the file.
But when I remove "\n"
from statements: printf("sugar\n")
, printf("salt\n")
, printf("spice\n")
,then I only get screen output as: "sugarsaltspice"
and nothing is stored in the file.
Please help me regarding this as I am not able to figure out why "\n"
makes a difference here.
Thanks a tonne.
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
int main()
{
int fd;
int o = dup(1); //backup of STD_OUT
fd = open("/home/Desktop/Text2.txt",O_CREAT|O_TRUNC|O_WRONLY,0);
printf("sugar\n");
dup2(fd,1); //CHANGE STD_OUT to FILE
printf("salt\n");
dup2(o,1); //Restore STD_OUT
printf("spice\n");
return 0;
}