Search code examples
c++filestreamzerostandards-compliance

std::ifstream::read or std::ofstream::write with a zero parameter?


Is it perfectly ok (= well defined behaviour 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 have to test if the provided size is null before calling one of these two functions.


Solution

  • Yes, the behavior is well-defined: both functions will go through the motions for unformatted input/output functions (constructing the sentry, setting failbit if eofbit is set, flushing the tied stream if necessary), and then they will get to this clause:

    §27.7.2.3[istream.unformatted]/30

    Characters are extracted and stored until either of the following occurs:

    — n characters are stored;

    §27.7.3.7[ostream.unformatted]/5

    Characters are inserted until either of the following occurs

    — n characters are inserted;

    "zero characters are stored/inserted" is true before anything is stored or extracted.

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