std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生

std::ifstream sets the eofbit at the point when the last item in the file is read, but it only happens when reading numerical types

本文关键字:读取 eofbit 设置 类型 取数值 文件 ifstream 最后 std 一项      更新时间:2023-10-16

>假设给定一个包含数字列表的非空文本文件,

1 2 3 4 5

我们用std::ifstream将它们读成数字类型(intdouble等(以及char

int main()
{
ifstream fs {"textfile.txt"};
int val {0}; //read into ints
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> val;
cout << val << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read                        
}
}

当读取为数值类型时,程序输出:

1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 010

在读取文件最后一项时,设置了 eofbit。

但是在读入char时不会发生同样的事情。

int main()
{
ifstream fs {"textfile.txt"};
char ch {0}; //read into chars
for (int i{0}; i < 5; ++i)
{
//read five times
fs >> ch;
cout << ch << " is read. Current state of file stream: "
<< bitset<3> (fs.rdstate()) << endl; //check stream state after each read                        
}
}

其中输出:

1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 000

为什么会这样呢?

读取ints 时会EOF,因为int的流提取运算符会尝试读取,直到找到空格或不适合int的内容。因此,它将在读取5后尝试读取另一个char,遇到文件的末尾并设置eofbit

相比之下,char的流提取运算符只会尝试读取一个char因此不会遇到文件的末尾。尝试从文件中读取 6char秒,您也会遇到EOF