我有一个名为readNextString(ifstream &file , char* &pBuffer)
的函数,它从文件中提取下一个字符串,直到达到','
或'\n'
,并移除字符串开头和结尾的空格,将剩余部分保存在pBuffer中,并返回true(如果一切正常) - 否则返回false。这个函数在遇到文件结尾之前都能正常工作,但是当eof
标志被设置时,无法移动get指针。我尝试了以下方法:
if(file.eof())
{
file.clear();
file.seekg(0 , ios::end)
}
删除字符串末尾的空格后,出现了问题。这个函数提取了没有空格的字符串,但是会进入无限循环。
我的实际问题是:如何检查下一个字符是否为EOF
,如果不能,是否有任何替代方法?
以下是我的实际函数:
bool readNextString(ifstream &file , char* &pBuffer)
{
if(file.eof()){
return false;
}
for(; file.good() && isWhitespace(file.peek()) && !file.eof() ; file.seekg(1 , ios::cur))
;
if(file.eof()){
cout << "The file is empty.\n";
return false;
}else{
streamoff startPos = file.tellg();
cout << "startPos : " << startPos << endl;
for(;file.good() && file.peek()!='\n' && file.peek()!=',' && file.peek()!= EOF; file.seekg(1 , ios::cur))
;
streamoff A = file.tellg();
cout << "A : " << A << endl;
file.seekg(-1 , ios::cur);
for(;file.good() && isWhitespace(file.peek()) ; file.seekg(-1 , ios::cur))
;
file.seekg(2 , ios::cur);
streamoff endPos = file.tellg();
cout << "endPos : " << endPos << endl;
pBuffer = new char[endPos-startPos];
if(pBuffer)
{
file.seekg(startPos , ios::beg);
file.get(pBuffer , endPos-startPos , ',' || '\n');
for(;file.good() && file.peek()!='\n' && file.peek()!=',' && file.peek()!= EOF; file.seekg(1 , ios::cur))
;
file.seekg(2 , ios::cur);
streamoff temp = file.tellg();
cout << "temp : " << temp << endl;
return true;
}else{
cout << "Error! Not enough memory to complete the task.\nPlease close some applications and try again.\n";
return false;
}
}
}
这是我所说的一个地方:
void printCities()
{
ifstream city ;
city.open("cities.txt", fstream::in);
if(city.is_open())
{
char *currCity;
int counter = 1;
while(readNextString(city , currCity))
{
cout << counter++ << ". " << currCity << endl;
delete[] currCity;
currCity = NULL;
}
if(city.eof())
cout << "There are no cities added.\n";
city.close();
}else
cout << "Error by opening 'cities.txt'.Make sure that the file exist and try again.\n";
}
希望我表达清楚了。如果您发现其他错误或可能的错误,我很高兴听到并从中学习。
istream
进行了缓冲。然而,使用seek
是慢的;在许多实现中,seek
将导致缓冲区丢失,并且每个字符需要两个系统调用。(它不必这样,但是在缓冲区内进行的寻址应该足够少,以至于库不会对它们进行优化。) - James Kanze