[英]Understanding file stream flags/bits
我認為我目前不太了解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
(此操作在這里沒有任何意義,但這只是為了了解行為)這些位中的一個)。
為了:
\n rdbuf()-> open(name,mode | std :: ios_base :: out);\n換句話說,`std :: ofstream`總是在打開時添加`out`位。
您可能會注意到,名稱並不總是很直觀: clear
可以設置,而且邏輯上與打開標志的關系也不是正交的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.