12

Warning:

warning C4244: 'initializing' : conversion from 'std::streamoff' to 'unsigned int', possible loss of data

Caused by:

unsigned int FileSize = File.tellg( ); // WARNING
std::cout << "Size = " << FileSize << std::endl;

Possible solution? Is it okay to do this:

// No more warnings but, is it safe?
unsigned int FileSize = (unsigned int)File.tellg( ); // OK?
std::cout << "Size = " << FileSize << std::endl;

How about this?

// No more warnings but, is it safe?
unsigned int FileSize = static_cast< unsigned int >( File.tellg( ) );
user2117427
  • 467
  • 2
  • 6
  • 10
  • Both solutions are fine. [I suggest you read up on casts](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used) – Cornstalks Mar 02 '13 at 08:16
  • Okay, I just wanted to make sure. – user2117427 Mar 02 '13 at 08:17
  • 2
    Is there a reason you don't want `std::streamoff FileSize = File.tellg();`? – Brent Bradburn Mar 02 '13 at 08:17
  • Yes both are fine as Cornstalks says - tellg() returns a streampos, which supports conversion to integer. – Roger Rowland Mar 02 '13 at 08:17
  • @nobar I am initializing a vector so I need to set the size. – user2117427 Mar 02 '13 at 08:18
  • 6
    It is fine only is you know *for sure* that the file will never be larger than what an `int` can hold. The warning is there because `std::streamoff` *can* hold larger values. You are not resolving the warning, but telling the compiler to shut up. – Bo Persson Mar 02 '13 at 11:04
  • Also, I just want to let you know that if you don't open the file in binary mode, `tellg()` – Cornstalks Mar 02 '13 at 16:20
  • 1. (unsigned int)() 2. static_cast< unsigned int >() Both solution do similar work. 1. C casting. 2. C++ casting. C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime. – user2856064 Jan 10 '17 at 10:59

1 Answers1

16

streamoff is a signed integral type defined by your C++ standard library implementation, and large enough to cater for the largest possible file sizes. In my x86_64 stdlibc++ for example, it is a int64_t.

In order to avoid potential data loss, use a larger type or... simply let your variable be of type streamoff.

us2012
  • 16,083
  • 3
  • 46
  • 62
  • I am trying to initialize the size of a vector. Which means, the size can't be negative and steamoff can handle negative and positive integers. – user2117427 Mar 02 '13 at 08:20
  • 4
    If *your* streamoff variable can actually be negative, then you have to *check* for that condition in your code. Simply casting your negative signed value to an unsigned one will always cause problems. – us2012 Mar 02 '13 at 08:22