question on ifstream::getline()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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
--------------------------------------

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux