File input in C++

deliciousMammal

Registered
Hello C++ coders.
I was just wondering about good coding style for inputting files of unknown length into a variable. Currently I have something like this:

ifstream file;
file.open(filePath);
while (file) {
++length;
file.get();
}

And then I use new to initialize an array of chars and then close the file, reopen it, and go through it for length times setting each member of the new array as I go.

Is there a better way to do this? I figure there probably is, so any help would be appreciated. Thanks.
 
Why don't you simply do a SEEK to the end of the file (which will give you the exact size), then read in exactly that number of bytes? That way, you'll only loop through the file once, plus you'll be able to read in chunks which is a hell of a lot more efficient than reading one character at a time...
 
Back
Top