c++ - How are the iostate bits affected by fstream.close() and subsequent .open()? -
c++ - How are the iostate bits affected by fstream.close() and subsequent .open()? -
i've got ofstream
object i'm periodically reopening, new filename. know .clear()
resets iostate
goodbit
. however, it's not clear me if state affected .close
, .open
.
in particular, can check .fail()
after .close()
determine whether should ::remove
file? don't want maintain corrupted or partial files.
and if badbit
and/or failbit
unaffected .close
, should explicitly .clear
them before calling .open(newpath)
? found out bits cleared .open
, formally since c++11 informally implementations did anyway.
from [ifstream.members] / 5:
void close();
effects: calls rdbuf()->close()
and, if function returns null pointer, calls setstate(failbit)
(which may throw ios_base::failure
(27.5.5.4)).
summing [filebuf.members] / 6:
basic_filebuf<chart,traits>* close();
is_open() == false
, returns null pointer. if of calls made function [...] fails, close
fails returning null pointer. if set area exists, calls overflow(traits::eof())
flush characters. if lastly virtual fellow member function called on *this
(between underflow
, overflow
, seekoff
, , seekpos
) overflow
calls a_codecvt.unshift
finally [...] function closes file (as if calling std::fclose(file)
) overflow
([filebuf.members] / 10) fails when:
codecvt::out
fails if codecvt
"encountered character not convert" ([locale.codecvt.virtuals] / 5). file output fails (unspecified, if fwrite
fails on implementations). codecvt::unshift
fails if "an unspecified error has occurred" ([locale.codecvt.virtuals] / 8).
std::fclose
fails "if errors detected." (c11 7.21.5.1).
in particular, can check .fail() after .close() determine whether should ::remove file?
as have seen, close
can fail if there problem file itself, or if codecvt comes across character cannot convert (or in unlikely event unshift
fails). if need absolutely sure close
failed because of file issue, need os.seekp(0, os.end).clear();
before closing create sure thing close
phone call std::fclose
.
c++
Comments
Post a Comment