Is it allowed to write to a ofstream when it is not opened in c++

删除回忆录丶 提交于 2019-11-28 05:45:29

问题


I have a code like this:

# in class definition
std::ofstream m_myFile;

## some where in code
m_myFile.open(filename);

and then in several places, I am writing to file as follow:

m_myFile << "some data to file"<<std::endl;

This is working well, now I need to add a flag to system that when not set, this file should not be created and written to. I have checked and I can run the application if I do this:

if(createFile)
{
      m_myFile.open(filename);
}

and leave the write to file as it is and I am not getting any runtime error on windows. My question is if I am not opening a file and write to its stream, what is the standard behaviour?

Should I get a run time error or the ofstream just forget about the data and not run time error?

I am using Visual Studio 2013.


回答1:


The standard behavior is that the first write fails. This sets the std::ofstream::badbit and further writes are silently ignored.

This silent failure could be changed to an exception by setting m_myFile.exceptions(std::ofstream::badbit), but it's off by default.

You can make any stream (even std::cout) discard its output by creating a "dev null" streambuf and then switching your stream to that buffer (via .rdbuf)




回答2:


If you don't open the file you have a stream with a default constructed file buffer that is being written to and will get discarded when the ofstream is discarded.



来源:https://stackoverflow.com/questions/28499630/is-it-allowed-to-write-to-a-ofstream-when-it-is-not-opened-in-c

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