Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ resolving istream::tellg warning

Tags:

c++

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( ) );
like image 763
user2117427 Avatar asked Mar 02 '13 08:03

user2117427


1 Answers

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.

like image 78
us2012 Avatar answered Sep 18 '22 11:09

us2012