Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...