簡體   English   中英

了解文件流標志/位

[英]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 (此操作在這里沒有任何意義,但這只是為了了解行為)這些位中的一個)。


為了:

  1. 您正在`std :: ofstream`上調用open。 std :: ofstream :: open的定義是:
    \n rdbuf()-> open(name,mode | std :: ios_base :: out);\n
    換句話說,`std :: ofstream`總是在打開時添加`out`位。
  2. 您可以在模式標志中添加`std :: ios_base :: app`,但這將強制每次寫入文件末尾,無論您之前位於何處。 (如果僅以寫操作打開,這可能就是您想要的。)否則,如果同時使用`std :: ios_base :: in和`sdt :: ios_base :: out`打開,則文件不會被截斷。
  3. 該文件不會被截斷:-)。 盡管`ofstream`不提供任何讀取功能,但是您可以從`rdbuf`返回的`streambuf`中創建一個`std :: istream`並從中讀取。
  4. 在這種情況下,stream.clear(std :: ios_base :: eofbit)可以解決問題。 但是您不能總是重置`badbit`:如果沒有附加`streambuf`,無論您做什么,都會設置`badbit`。

您可能會注意到,名稱並不總是很直觀: clear可以設置,而且邏輯上與打開標志的關系也不是正交的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM