Rerouting stdin and stdout from C

前端 未结 8 1396
终归单人心
终归单人心 2020-11-22 12:15

I want to reopen the stdin and stdout (and perhaps stderr while I\'m at it) filehandles, so that future calls to printf()

8条回答
  •  心在旅途
    2020-11-22 12:45

    Why use freopen()? The C89 specification has the answer in one of the endnotes for the section on :

    116. The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

    freopen is commonly misused, e.g. stdin = freopen("newin", "r", stdin);. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");. Both expressions attempt to assign to stdin, which is not guaranteed to be assignable.

    The right way to use freopen is to omit the assignment: freopen("newin", "r", stdin);

提交回复
热议问题