G
Generic Usenet Account
I have been able to recreate a problem that I am having with the file
stream using the simple sample code given below.
I am trying to read the number of lines in a file, relying on the
getline method to read all the characters (including leading
whitespaces) until the new line character (the default line delimiter)
or end-of-file is reached. Then I close the stream, reopen it and
repeat the procedure. I get the correct answer only the first time.
The second time I get value of zero. This is with gcc version 3.3.1
Is this a compiler issue, or is this standard language feature?
Sample code follow
Thanks,
Song
///////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
main(int argc, char* argv[])
{
if(argc < 2)
{
cerr << "usage: " << argv[0] << " <filename>" << endl;
exit(-1);
}
ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}
// First pass
string token;
unsigned long nlCount = 0;
while(getline(fileStrm, token))
nlCount++;
fileStrm.close();
cout << nlCount << "\n";
// Second pass
fileStrm.open(argv[1]);
nlCount = 0;
while(getline(fileStrm, token))
nlCount++;
fileStrm.close();
cout << nlCount << "\n";
exit(0);
}
stream using the simple sample code given below.
I am trying to read the number of lines in a file, relying on the
getline method to read all the characters (including leading
whitespaces) until the new line character (the default line delimiter)
or end-of-file is reached. Then I close the stream, reopen it and
repeat the procedure. I get the correct answer only the first time.
The second time I get value of zero. This is with gcc version 3.3.1
Is this a compiler issue, or is this standard language feature?
Sample code follow
Thanks,
Song
///////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
main(int argc, char* argv[])
{
if(argc < 2)
{
cerr << "usage: " << argv[0] << " <filename>" << endl;
exit(-1);
}
ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}
// First pass
string token;
unsigned long nlCount = 0;
while(getline(fileStrm, token))
nlCount++;
fileStrm.close();
cout << nlCount << "\n";
// Second pass
fileStrm.open(argv[1]);
nlCount = 0;
while(getline(fileStrm, token))
nlCount++;
fileStrm.close();
cout << nlCount << "\n";
exit(0);
}