Reputation: 100
So I have a question regarding the use of ofstream in a while loop. Say I had an array of size X
and I wanted to loop though that array and output the items to file. Would the following code be sufficent for error checking? If so (or not so) why?
char arr[X];
ofstream fout("out.txt");
for(int i=0;i<X;i++)
{
while(!(fout<<arr[i]){}
}
Upvotes: 1
Views: 158
Reputation: 153820
When writing char
s there aren't too many things which can go wrong. The only error which may occur is that the stream's std::streambuf
reports an error in overflow()
. This adequately tested by your test. That said, successfully buffering characters doesn't mean that writing the buffer will be successful. To test for a successful write you'll also need to test if fout.close()
is successful! The implicit close()
in the destructor will just swallow any errors.
Note, however, that once the stream went into failure state it would stop doing anything useful until clear()
is called on the stream. Put differently, if there is an error while writing to the stream, you'll just end up with an infinite loop. Even with a call to clear()
I wouldn't expect that an underlying stream buffer would do anything different, i.e., I would expect it to just fail again. That is, if you really care about these errors you'll need to come up with a better error handling strategy than "try again"!
Upvotes: 2