0

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;
}
blatinox
  • 748
  • 5
  • 16
Xeqtr
  • 13
  • 1
  • 7
  • Why you cannot use `fprintf()`? – Sourav Ghosh Jul 13 '16 at 10:27
  • Thanks for your reply Sourav. I can use fprintf() but I was just trying things out and came across this. – Xeqtr Jul 13 '16 at 10:30
  • You can use standard `freopen()` func to redirect `stdout` to whatever you want. – Sergio Jul 13 '16 at 10:40
  • Thanks @Serhio , will try it out ,never used it..and by the way the answer to my question is that "/n" is providing the fflush(stdout) which we have to explicitly mention if not using "/n". – Xeqtr Jul 13 '16 at 10:44
  • Oh, my comment is just a small note about redirection approach, not about question itself. – Sergio Jul 13 '16 at 10:48
  • Thanks @Serhio,I learnt a new function freopen() :). – Xeqtr Jul 13 '16 at 10:54
  • I don't think that this question is a duplicate. It is more about a specific problem with buffered streams wich could be explained in detail than the generic question about "Why does `printf` not work?" – muXXmit2X Jul 13 '16 at 10:55
  • @muXXmit2X I did try to search but couldn't really find answer and I am pretty new here ,maybe next time I shall dig little deeper. – Xeqtr Jul 13 '16 at 11:01

0 Answers0