Warm tip: This article is reproduced from stackoverflow.com, please click
c c++ stdin stream freopen

Is it allowed to use freopen with "w+" mode for stdin?

发布于 2020-04-23 12:40:39

Consider the following code:

freopen("buffer.txt", "w+", stdin);
fprintf(stdin, "hello");
fseek(stdin, 0, SEEK_SET);
char str[16];
scanf("%s", str);
printf("%s", str);

I've found no entries in standard restricting me from doing that, but also no entries explicitly allowing it. Should I expect this code to work on any standard compliant compiler? Would any standard i/o function break or lead to UB if stdin (or stdout) is opened in read-write mode? What about c++ streams?

Questioner
Denis Sheremet
Viewed
38
NutCracker 2020-02-09 17:55

From C++ standard for freopen function:

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

mode

C string containing a file access mode. It can be:

...

w+ - write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.

So, by standard it is perfectly legal.

However, if you want to be more sure, then check if the return value is null pointer or not. Or even more, check the errno variable if it is set to a system-specific error code on failure.

Furthermore, if you take a closer look at the freopen docs, you will see the following sentence:

This function is especially useful for redirecting predefined streams like stdin, stdout and stderr to specific files.

This is one more confirmation it is legal to use w+ for stdin.