This question already has an answer here:
I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream
class from the fstream
header?
This question already has an answer here:
I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream
class from the fstream
header?
You can seek until the end, then compute the difference:
Don't use
tellg
to determine the exact size of the file. The length determined bytellg
will be larger than the number of characters can be read from the file.From stackoverflow question tellg() function give wrong size of file?
tellg
does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:
I'm a novice, but this is my self taught way of doing it:
Like this:
You can open the file using the
ios::ate
flag (andios::binary
flag), so thetellg()
function will give you directly the file size: