了解文件流标志/位

时间:2012-10-05 13:44:09

标签: c++ iostream fstream flags

我认为我目前还不太了解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(这个操作在这里没有意义,但只是理解这些位的行为)。


1 个答案:

答案 0 :(得分:1)

按顺序:

  1. 你在`std :: ofstream`上打开。的定义 `std :: ofstream :: open`是:
    rdbuf()->open( name, mode | std::ios_base::out );
    
    换句话说,`std :: ofstream`在打开时总是添加`out`位。
  2. 您可以将`std :: ios_base :: app`添加到模式标志中,但这样会 具有强制每次写入到文件末尾的效果,无论如何 以前你可能在哪里定位。 (这可能是你想要的 如果你只是以书面形式开场。)否则,如果你同时打开 `std :: ios_base :: in`和`sdt :: ios_base :: out`,文件不会是 截断。
  3. 该文件不会被截断:-)。虽然`ofstream`没有提供 任何从它读取的函数,你都可以创建一个`std :: istream` `rdbuf`返回的`streambuf`,并从中读取。
  4. 在这种情况下`stream.clear(std :: ios_base :: eofbit)`会做的 特技。但你不能总是重置`badbit`:如果没有`streambuf` 无论你做什么,都会设置`badbit`。

您可能会注意到,名称并不总是直观的:clear要设置 有点,逻辑与开放的逻辑相差甚远 标志。