运用ifstream的getline时需要注意的问题
来源:互联网 发布:移动公司网络维修电话 编辑:程序博客网 时间:2024/05/29 10:09
我们在应用中经常会遇到从文件中读行的操作,
当然方法有多种,这里我想和大家探讨一下用ifstream的getline方法:
主要code如下:
……
const int MAXLEN = 256;
std::vector<std::string> vecFilelines;
std::ifstream fs("test.txt");
if (fs.good())
{
char stringline[MAXLEN];
while (!fs.eof())
{
fs.getline(stringline, MAXLEN);
vecFilelines.push_back(stringline);
}
}
……
初步看一下上面的代码没什么问题,
如果你所要读的每一行的长度不超过255,程序运行也不会有问题
但当你所要读的长度超过了255,就有问题了,我尝试的现象是:
当读到第一个超过255的行时,程序会陷入死循环,内存会被慢慢耗尽。
经过对istream里getline方法的分析,找出原因如下:
……
_Myt& __CLR_OR_THIS_CALL getline(_Elem *_Str,
streamsize _Count, _Elem _Delim)
{ // get up to _Count characters into NTCS, discard _Delim
_DEBUG_POINTER(_Str);
ios_base::iostate _State = ios_base::goodbit;
_Chcount = 0;
const sentry _Ok(*this, true);
if (_Ok && 0 < _Count)
{ // state okay, use facet to extract
int_type _Metadelim = _Traits::to_int_type(_Delim);
_TRY_IO_BEGIN
int_type _Meta = _Myios::rdbuf()->sgetc();
for (; ; _Meta = _Myios::rdbuf()->snextc())
if (_Traits::eq_int_type(_Traits::eof(), _Meta))
{ // end of file, quit
_State |= ios_base::eofbit;
break;
}
else if (_Meta == _Metadelim)
{ // got a delimiter, discard it and quit
++_Chcount;
_Myios::rdbuf()->sbumpc();
break;
}
else if (--_Count <= 0)
{ // buffer full, quit
_State |= ios_base::failbit;
break;
}
else
{ // got a character, add it to string
++_Chcount;
*_Str++ = _Traits::to_char_type(_Meta);
}
_CATCH_IO_END
}
*_Str = _Elem(); // add terminating null character
_Myios::setstate(_Chcount == 0 ? _State | ios_base::failbit : _State);
return (*this);
}
……
当你读到一个大于255的行时,由逻辑
else if (--_Count <= 0)
{ // buffer full, quit
_State |= ios_base::failbit;
break;
}
会将文件的_State置为ios_base::failbit,从而_Ok变成false
而后再继续getline时,_Ok将会一直为false,而getline会一直返回空串,在while中陷入死循环。
改善如下:
……
const int MAXLEN = 256;
std::vector<std::string> vecFilelines;
std::ifstream fs("test.txt");
if (fs.good())
{
char stringline[MAXLEN];
while (!fs.eof())
{
if (fs.getline(stringline, MAXLEN).good())
{
vecFilelines.push_back(stringline);
}
else
{
// add you logic to deal with the unexpected situation
break;
}
}
}
……
如有不对之处,还请高手及时指出,谢谢!
- 运用ifstream的getline时需要注意的问题
- 原创:运用ifstream的getline时需要注意的问题
- 运用ifstream的getline时需要注意的问题
- ifstream.getline()的陷阱
- socket运用中需要注意的一个问题
- getline的获取ifstream的数据
- “ifstream类的getline函数”和“getline函数”的区别
- ofstream ifstream getline 对文件的操作 !
- getline和ifstream<<读文件的方式
- 运用mysqldump 工具时注意的问题
- 需要注意的问题
- 需要注意的问题
- 运用Recycleview经常出现的问题及需要注意的地方
- 使用ProGuard时需要注意的问题
- 安装svnmanager 时需要注意的问题
- 选择框架时需要注意的问题
- 降低HWM时需要注意的问题
- 指针使用时需要注意的问题
- 05-防盗链技术
- HDU 1285 拓扑排序
- linux遍历目录下的文件
- 尼姆博弈
- 使用WinSetupFromUSB来U盘安装windowsXP
- 运用ifstream的getline时需要注意的问题
- POJ 3259 最短路径
- 使用ifstream和getline读取文件内容[c++]
- std::string用法总结
- shellcode编写技巧
- PYTHON 双引号 单引号 多引号区别
- 淘宝指数批量查询工具v1.8 正式发布
- hdu2578(二分法)
- HDU 1251 字典树