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

試著忘記壹切 提交于 2019-12-10 13:29:56

问题


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.


回答1:


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




回答2:


Another extraction from 27.7.2.3 Unformatted input functions/1 gives us a clue that zero-size input buffers are valid case:

unformatted input functions taking a character array of non-zero size as an argument shall also store a null character (using charT()) in the first location of the array.



来源:https://stackoverflow.com/questions/13014192/stdifstreamread-or-stdofstreamwrite-with-a-zero-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!