2006-11-18

[有進步] Once I've used freopen, how can I get the original stdout (or stdin) back?

今天遇到的,有進步。

http://c-faq.com/stdio/undofreopen.html


FILE *fp;
freopen("foo.txt", "w", stdout);
fprintf(fp, "Hello, World\n");
fclose(fp);
printf("Hello, World2\n");


#Output
Hello, World2

And the "Hello, World" is write into *fp points to, "foo.txt".


Mistake example


    FILE *fp = freopen("foo.txt", "w", stdout);
    printf("Hello, World\n");
    fclose(fp);
    printf("Hello, World2\n");


    #Output
    (nothing)

    Because the "Hello, World" was be redirect to "foo.txt", althought it was already excused fclose(fp), but we got nothing from stdout. So the better way is to using fprintf().

沒有留言: