0

I am interested in knowing the size of a file in C++ using the stream classes of stl.

In order to accomplish that, long ago, I opened the file and then I performed some such as:

file.seekp(0, ios_base::end); // another way is open file with ios::ate mode
unsigned long file_size = file.tellp();

According to the file type and the access mode, the same thing could be accomplished with seekg() and tellg().

However, reading a little about the doc, especially the Josuttis book about the stl, I see that the return type of tellp() is pos_type and not unsigned long or any similar type (size_t, ...).

This way of knowing the file size works still, at least for binary files, but I am not conform because I am not sure about its safety and portability given the fact that pos_type could not cast correctly to an unsigned long.

So I have the following questions:

  1. Is this way for knowing the file size (the mine) still sure? should I change it?
  2. there are other ways?
lrleon
  • 2,610
  • 3
  • 25
  • 38
  • 4
    Is this same question as this one http://stackoverflow.com/a/5840160/1068199 ? – LukasT Nov 11 '15 at 12:18
  • 2
    Change `file_size` to `pos_type` (or `auto`)? – Emil Laine Nov 11 '15 at 12:18
  • @zenith The duplicated question gives enough account about the mine. Thanks for being aware. However, I would have not marked it as duplicate so fast, because it aborts different edges of discussion that may be of interest. For instance, if the same thing is accomplished indistinctively with `tellg()` and `tellp()`. Anyway, thanks. Regards – lrleon Nov 11 '15 at 12:34
  • If you don't agree that it's a duplicate, edit your question explaining why you think it isn't and how it differs; more details [here](https://stackoverflow.com/help/reopen-questions). – edmz Nov 11 '15 at 13:22

0 Answers0