Std :: ifstream :: read or std :: ofstream :: write with a null parameter?

It is normal (= well-defined behavior according to the standard) to call:

mystream.read(buffer, 0); 

or

 mystream.write(buffer, 0); 

(and, of course, nothing will be read or written). I would like to know if I should check if the provided size is zero before calling one of these two functions.

+6
source share
2 answers

Yes, the behavior is clearly defined: both functions will go through movements for unformatted I / O functions (building a sentry, setting failbit, if eofbit is installed, clearing the associated stream if necessary), and then they will get to this section:

ยง27.7.2.3 [istream.unformatted] / 30

Symbols are retrieved and stored until the following happens:

- n characters are stored;

ยง27.7.3.7 [ostream.unformatted] / 5

Characters are inserted until the following happens:

- n characters are inserted;

"null characters are saved / inserted" is true before something is saved or retrieved.

Looking at the actual implementations, I see for (; gcount < n; ++gcount) in libC ++ or sgetn(buffer, n); in stdlibC ++ , which has an equivalent loop

+8
source

Another extract from 27.7.2.3 Unformatted input functions/1 makes it clear that zero-size input buffers are a valid case:

unformatted input functions that accept an array of characters of nonzero size as an argument must also store the zero character (using charT ()) at the first location of the array.

0
source

All Articles