Home > database >  C program prints to terminal instead of file even after using dup2/dup
C program prints to terminal instead of file even after using dup2/dup

Time:01-02

I'm in an operating systems course and doing assignments with C on Linux. In one of the assignments I was supposed to redirect and output to a file, but for some reason, I keep getting the output in the terminal instead. I tried writing a simple program to do just that and it still didn't work:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>

void main(int argc, char* argv[]) {
    int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
    printf("write to screen\n"); //print to screen
    int oldOut = dup(1); //save screen FD
    dup2(file1,1); //change output stream from screen to file
    printf("write to file"); //print to file
    dup2(oldOut,1); //change output stream from file back screen 
    printf("write to screen");  //print to screen
}

other things I tried :

  1. changing the permissions on the file open (adding O_RDWR)
  2. running on 2 separate PCs - i run mainly on remote desktop to the uni pc for linux but also got VMware on the laptop.
  3. tried using close dup combo instead on dup2
  4. tried using conditions with perror to see if any step will tip me off as to why it doesn't work.
  5. tried using STDOUT_FILENO instead of 1 for output

would really appreciate any help on this!

CodePudding user response:

stdio normally buffers output to stdout -- it's line-buffered when it's connected to a terminal, fully-buffered when connected to a file. Since you're not writing any newlines, it will not flush the buffer automatically in either mode. The buffer is flushed automatically when the program exits, at which time it gets written to the last stream that FD 1 is connected to.

Either turn off buffering with setvbuf(), or flush the output explicitly between printf() calls.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>

void main(int argc, char* argv[]) {
    int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
    printf("write to screen\n"); //print to screen
    int oldOut = dup(1); //save screen FD
    dup2(file1,1); //change output stream from screen to file
    printf("write to file"); //print to file
    fflush(stdout);
    dup2(oldOut,1); //change output stream from file back screen 
    printf("write to screen");  //print to screen
    fflush(stdout);
}
  • Related