【发布时间】:2012-10-05 13:44:08
【问题描述】:
我认为我目前不太了解 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 重置为 false 并将 eofbit 设置为 true (这个操作在这里没有意义,只是为了了解这些位的行为)。
【问题讨论】:
标签: c++ iostream fstream flags