Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirecting standard output in c then resetting standard output

Tags:

c

unistd.h

fcntl

I'm trying to use redirects in C to redirect input to one file and then set standard output back to print to the screen. Could someone tell me what's 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;
}
like image 511
David Avatar asked Jul 24 '11 07:07

David


2 Answers

One thing you'll have to make sure to do before that will work at all, is to call fflush(stdout); before switching the stdout file descriptor out from under it. What's probably happening is that the C standard library is buffering your output, unaware that you're shifting around the file descriptors underneath it. The data you write using printf() isn't actually sent to the underlying file descriptor until its buffer becomes full (or your program returns from main).

Insert the call like this:

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

before both calls to dup2().

like image 51
Greg Hewgill Avatar answered Sep 20 '22 00:09

Greg Hewgill


Your second dup2 call is wrong, replace with:

if (dup2(current_out, 1) < 0) {
like image 31
Mat Avatar answered Sep 19 '22 00:09

Mat