关于缓冲(setvbuf())的freopen()的预期行为?

In an attempt to implement freopen(), I've come up to a piece of specification in the standard that doesn't actually specify anything, as far as I can see.

So... freopen() will close the stream (ignoring errors), clear its error and EOF flag, reset wide orientation, and then reopen the stream with the given mode. That much is clear; this is basically an fclose() / fopen(). Even if it isn't defined that way, it is pretty clear that this is what was intended.

However, I have two questions with regards to the things setvbuf() could have done to the stream -- setting a user-allocated buffer, and / or changing buffer policy.

问题1

1) Is freopen() expected to revert things to the default state, as if it had actually called fopen()? Or is it expected to carry over to the new stream whatever the user did set via setvbuf() on the old? This refers to both buffer memory and buffer policy, but the main issue here is with buffer memory.

The specification for fclose() specifies that any buffer the user associated with the stream via setvbuf() is disassociated, i.e. can now be free()'d by the user.

But freopen() only specifies that it closes the file associated with the stream, not that it fclose()es it.

So, after freopen(), is user-associated buffer memory still associated with the stream?

问题2。

freopen() can conceivably be used on a FILE structure that is not actually associated with an open file at the time of the call (as errors trying to close the file are to be ignored).

That file structure could have been a previously open stream with user-assigned buffer memory and buffer policy. Is freopen() to honor these settings, i.e. re-associate the buffer memory / policy with the "re"-opened file, or is it to reinit the structure to defaults, assuming the user free()d the buffer memory after fclose()ing the file previously?

我拿

Looking at Q2, I don't see a way for the standard library to reliably determine whether a not-currently-open FILE structure with user-allocated buffer memory still "owns" that buffer memory, or whether the user has already reclaimed that memory. (That memory could conceivably be local, i.e. not part of the memory lists handled by malloc() / free().)

缓冲策略的类似考虑。

So the only reliable way of handling things, as far as I can see, is for freopen() to handle the closing of "any file that is associated with the specified stream" as a "real" fclose(), and re-set buffer memory / policyto defaults.

我对这种理解是否正确,还是对Q1 / Q2有替代答案?

评论