读取文件时避免错误标志
Avoiding Error Flags when Reading Files
我通常是这样读取std::ifstream
:
while (InFile.peek() != EOF)
{
char Character = InFile.get();
// Do stuff with Character...
}
这避免了在循环内使用if
语句的需要。然而,似乎甚至peek()
导致eofbit
被设置,这使得调用clear()
是必要的,如果我计划以后使用相同的流。
有更干净的方法吗?
通常,您只需使用
char x;
while(file >> x) {
// do something with x
}
// now clear file if you want
如果您忘记清除(),那么使用基于RAII作用域的类。
编辑:如果有更多的信息,我就直接说class FileReader {
std::stringstream str;
public:
FileReader(std::string filename) {
std::ifstream file(filename);
file >> str.rdbuf();
}
std::stringstream Contents() {
return str;
}
};
现在您可以只获得一个副本,而不必每次都清除()流。或者你可以有一个自清除引用。
template<typename T> class SelfClearingReference {
T* t;
public:
SelfClearingReference(T& tref)
: t(&tref) {}
~SelfClearingReference() {
tref->clear();
}
template<typename Operand> T& operator>>(Operand& op) {
return *t >> op;
}
};
我不太明白。Infile.peek()
只设置eofbit
当它返回EOF
。如果它返回EOF
,然后读取注定要失败;它设置eofbit
的事实是一个优化,比什么都重要
相关文章:
- 有关使用标志位设置内部错误标志的说明
- Clang:覆盖之前在命令行上指定的所有警告和错误警告标志
- std::function, Clang 6.0 & MSVC (10.0017134.12) - 可能的 ABI 错误或必需的编译器标志
- 为什么在编译过程中尽管有 -I(破折号大写 i)标志,但仍会出现未定义的引用错误?
- 为什么我必须将错误状态标志设置为 goodbit 才能使其工作
- C - iStream错误标志
- 链接QT5库会自动将额外的FPIC标志传递给NVCC编译器,并通过cmake Cause错误
- 安装XLNT后,具有-lxnt标志的G 错误
- 用错误的标志顺序编译后,是否删除*.cpp文件
- 可以清除流的单个错误状态标志
- std::ostringstream将标志放在错误的位置
- 为什么std::istringstream在没有引发故障位标志的情况下生成错误的结果
- 优化标志会导致计算错误
- 使用 ios::Nocreate 标志会导致"undeclared identifier"错误
- 标志 ios_base::app 的错误行为
- GCC 错误错误的 ELF 类:ELFCLASS64,尽管有 -m64 标志
- 异常是否应具有标志/消息,或者每个错误应具有异常类型
- OpenCV错误:错误标志
- 有没有办法将 WinAPI 错误标志作为字符串获取
- 读取文件时避免错误标志