简体   繁体   中英

Output redirection in C

I'm trying to redirect output in C ( ./a.out > out.log ), I want printf to print to the file instead of stdout, for some reason I couldn't achieve that, I also can't understand what 'copy' means in dup2 description in the linux manual:

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary

Is copy means redirect?

Thanks for your help.

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

int main(){
  FILE *fout=fopen("out.log","wt");
  if(!fout)
    return 1;

  printf("Hi stdout\n");

  if(dup2(fileno(fout),fileno(stdout) == -1)) return 1;

  printf("Hi file\n");

  fclose(fout);

  return 0;
}

Yes, this is a means of redirection. Your code would work otherwise, except for the typo:

You're dupping to fd numbered fileno(stdout) == -1 ; since stdout is initially opened to file descriptor 1 , the comparison is 1 == -1 which is false; ie 0 and you end up dup2ing your new file descriptor over standard input instead of standard output.

Obviously the code should have been:

// notice the parentheses here      v
if (dup2(fileno(fout),fileno(stdout)) == -1) return 1;

Addendum, you probably would want to fflush the stdout before dupping, just to be sure - because the stdout might not be line buffered.

It is more portable to use the freopen to reopen stdout , but this will redirect only output from stdio functions, not the output from unix system calls or subprocesses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM