Get file byte size?

I

Immortal Nephi

Do C++ Standard Library have Get File Byte Size function in fstream
header? If not, I have to use C Run-Time library instead.
 
R

Robert Fendt

Do C++ Standard Library have Get File Byte Size function in fstream
header? If not, I have to use C Run-Time library instead.

You might try the following, without having it checked too thoroughly:

stream.seekg(0, std::ios_base::end);
std::streampos length = stream.tellg();
stream.seekg(0);


Regards,
Robert
 
J

James Kanze

Do C++ Standard Library have Get File Byte Size function in
fstream header?
No.

If not, I have to use C Run-Time library instead.

It's not available in standard C, either.

For starters: define what the function should return. Something
like File Byte Size is very vague, and can mean several
different things, and different things on different systems.
The two "useful" meanings I can think of would be: how many
bytes the file occupies on the disk, and how many bytes can I
read from it sequentially before reaching end of file. For the
first, as far as I know, neither Unix nor Windows provides a
means of determining this. For the second, you can use stat
under Unix, with reliable results. Under Windows, I'm not aware
of anything which will tell you how many bytes you can read from
an ifstream opened in text mode, other than actually reading it.
(GetFileSize returns the number of bytes which can be read using
ReadFile, which isn't the same thing.)
 
J

James Kanze

And thus spake Immortal Nephi <[email protected]>
Sat, 13 Feb 2010 21:10:28 -0800 (PST):
You might try the following, without having it checked too thoroughly:
stream.seekg(0, std::ios_base::end);
std::streampos length = stream.tellg();
stream.seekg(0);

Well, it's certainly not guaranteed. For starters,
std::streampos isn't even an integral type---it's a class. And
there are very few guarantees regarding conversions of it to and
from an integral type---std::streampos(0) is guaranteed to be
the first position in the file, I think, but that's about it.

In practice, this will work under Unix. Under Windows, it will
usually result in a value that is somewhat larger than the file,
if the file was opened as a text file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top