我认为我目前不太了解 io 流标志的机制。为了试图理解这一点,我将就两个具体例子提出问题。
第一个涉及开放模式。例如,对于 std::ofstream 我们有:
void open ( const char * filename, ios_base::openmode mode = ios_base::out );
app (append) Set the stream's position indicator to the end of the stream before each output operation.
ate (at end) Set the stream's position indicator to the end of the stream on opening.
binary (binary) Consider stream as binary rather than text.
in (input) Allow input operations on the stream.
out (output) Allow output operations on the stream.
trunc (truncate) Any current content is discarded, assuming a length of zero on opening.
我有以下问题:
std::ofstream stream;
// Question 1 : Here I don't specify std::ios::out, so why does it work ? :
stream.open("file.txt", std::ios::binary);
// Question 2 : Here I activate trunc, but how can I deactivate it ?
stream.open("file.txt", std::ios:binary | std::ios::trunc);
// Question 3 : What would be the result of that ?
stream.open("file.txt", std::ios::in);
第二个与州旗有关。考虑以下示例:
std::ofstream stream;
std::cout<<stream.good()<<stream.bad()<<stream.fail()<<stream.eof()<<std::endl;
stream<<'x';
std::cout<<stream.good()<<stream.bad()<<stream.fail()<<stream.eof()<<std::endl;
/* SOMETHING */
由于没有打开文件,结果是:
1000 // <- Good bit is true
0110 // <- Fail and bad bit are true
问题4:我可以写什么代码来代替/* SOMETHING */
,重置badbit
tofalse
和设置eofbit
to true
(这个操作在这里没有意义,只是为了理解这些位的行为)。