C++: ios::app doesnt need ios::out in fstream

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

i was testing with flags in file stream objects the other day

And i did this.

fstream binf("h.txt", ios::app); binf << "hey";

With fstream since i didnt use ios::out, the output operation shouldnt have worked , but it does work

I noticed that the the output operation works with ios::app only but if i use any other flag without ios::out it doesnt work

Can anyone tell me why I was able to output to the file while using only ios::app without ios::out

回答1:

Using app implies out.

The standard specifies that app and out|app have the same result, equivalent to C fopen in mode "a".



回答2:

Well, appending implies writing, that's about the longest explanation I can come up with.



回答3:

This answer is more compiler specific,but they are amazing to be noticed:-


VS 2010 fstream :- ios_base::out flag is already set

explicit basic_ofstream(const char *_Filename,         ios_base::openmode _Mode = ios_base::out,         int _Prot = (int)ios_base::_Openprot)         : _Mybase(&_Filebuffer)         {            if (_Filebuffer.open(_Filename, _Mode | ios_base::out, _Prot) == 0)             _Myios::setstate(ios_base::failbit);         }

GCC 4.5 fstream:- Again ios_base::out flag is already set

explicit       basic_ofstream(const char* __s,              ios_base::openmode __mode = ios_base::out|ios_base::trunc)       : __ostream_type(), _M_filebuf()       {     this->init(&_M_filebuf);     this->open(__s, __mode);       }  void       open(const char* __s,        ios_base::openmode __mode = ios_base::out | ios_base::trunc)       {     if (!_M_filebuf.open(__s, __mode | ios_base::out))       this->setstate(ios_base::failbit);     else       this->clear();       }

And even more interesting thing is, only in ios_base::in the last bit is a 1.Which signifies ios_base::in is able to retain its identity even raised with flag ios_base::out.



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