This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
question on ifstream::getline()
- From: "Jim the Standing Bear" <standingbear at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Thu, 27 Jul 2006 22:55:23 -0400
- Subject: question on ifstream::getline()
I have a question regarding ifstream.getline(). According to
cplusplus reference, ifstream.getline(buffer, num) is supposed to get
(num - 1) of characters or '\n', which ever comes first. However, in
my case, if the line length is more than (num), it will kill the
stream by setting the fail status. Is this behavior normal? Or is
this an odd behavior of g++? Thanks. I am using g++ v3.4.6
int countLines(char* filename, bool verbose) {
ifstream ifs;
int lineCount = 0;
char randtext[TEXT_WIDTH + 1];
ifs.open(filename);
if (!ifs) {
cerr << "Error: unable to open " << filename <<endl;
exit(1);
}
ifs.getline(randtext, TEXT_WIDTH);
while (!ifs.eof()) {
lineCount++;
if (verbose) {
cout << "Reading line " << lineCount << ": " << randtext << endl;
}
ifs.getline(randtext, TEXT_WIDTH);
cout << ifs.tellg() << endl;
if (int(ifs.tellg()) == -1) {
cout << ifs.bad() <<endl;
cout << ifs.eof() <<endl;
cout << ifs.fail() << endl; //////////// oddly enough, when
there is a long line, the fail bit will be set and the file goes into
an infinite loop...
exit(-1);
}
}
ifs.close();
return lineCount;
}
--
--------------------------------------
Standing Bear Has Spoken
--------------------------------------