【问题标题】:Understanding file stream flags/bits了解文件流标志/位
【发布时间】: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


    【解决方案1】:

    按顺序:

    1. 您在 `std::ofstream` 上调用 open。的定义 `std::ofstream::open` 是: rdbuf()->open( 名称,模式 | 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 设置 有点,关于开放的逻辑远非正交 标志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多