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
>假设给定一个包含数字列表的非空文本文件,
1 2 3 4 5
我们用std::ifstream
将它们读成数字类型(int
、double
等(以及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
为什么会这样呢?
读取int
s 时会EOF
,因为int
的流提取运算符会尝试读取,直到找到空格或不适合int
的内容。因此,它将在读取5
后尝试读取另一个char
,遇到文件的末尾并设置eofbit
。
相比之下,char
的流提取运算符只会尝试读取一个char
因此不会遇到文件的末尾。尝试从文件中读取 6char
秒,您也会遇到EOF
。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生