我认为我目前还不太了解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
并设置{ {1}}到eofbit
(这个操作在这里没有意义,但只是理解这些位的行为)。
答案 0 :(得分:1)
按顺序:
rdbuf()->open( name, mode | std::ios_base::out );换句话说,`std :: ofstream`在打开时总是添加`out`位。
您可能会注意到,名称并不总是直观的:clear
要设置
有点,逻辑与开放的逻辑相差甚远
标志。