Re: Reading from file line by line
"Peter Schmitz" <PeterSchmitz@discussions.microsoft.com> wrote in
message news:148A11DC-3E8B-4F90-B492-5773CD9E5E89@microsoft.com
Thanks for replying. unfortunately, I somtimes encounter a problem: I
need to read quite big files (4,5MB) line by line. If I run the code
you specified (I just added a if(!f.good())break; statement), good()
always returns false and therefore the read process stops.
Are you saying f.good() becomes false after some initial portion of the
file is read? Or is it false right away? If the latter, it means opening
the file has failed - e.g. because you are passing a wrong file name, or
the file is already open elsewhere.
This does
not happen if I split the file into several small files....
I don't see how the size of the file can affect this program (as long as
you don't get near 2GB large or larger). This program works for me:
#include <assert.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
static const int N = 1000000;
assert(argc > 1);
// Write a large file
ofstream ofs(argv[1]);
for (int i = 0; i < N; ++i) {
ofs << "A line of text\n";
}
ofs.close();
// Read it back, count lines
ifstream ifs(argv[1]);
int n = 0;
for (;;) {
string line;
getline(ifs, line);
if (!ifs) break;
++n;
}
ifs.close();
cout << n << " lines" << endl;
return 0;
}
N=1000000 produces a 12MB+ large file.
Is there a way to get a specific error message from ifstream, rather
than just a boolean?
No, as far as I know. But you can set the stream to throw an exception
on failure:
f.exceptions(ios::badbit | ios::failbit);
You will then be dropped into debugger when exception occurs, and could
hopefully figure out from the source code where exception was thrown
exactly what went wrong.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925