I have this code:
m_file.seekg(0, std::ios_base::end);
int fileSize = (int)(m_file.tellg());
m_file.seekg(0, std::ios_base::beg);
m_fileContent.resize(fileSize);
m_file.read(m_fileContent.data(), fileSize);
the idea is to read the content of a binary file into a vector. This code is compiled and run well, but I am not sure this line is correct in a c++ environment?
int fileSize = (int)(m_file.tellg());
Am I using the correct cast? It is ac style cast and not a c++ one. I tried this cast but it generate compiler error:
int fileSize = reinterpret_cast<int>(m_file.tellg());
but I am getting this error:
'reinterpret_cast' : cannot convert from 'std::fpos<_Mbstatet>' to 'int'
what is the best way to cast value types to each other? Should I use C style cast or C++ style cast?
您根本不需要演员,而是使用
size_t fileSize = file.tellg();
You shouldn't be casting at all, but rather (assuming C++11) using auto
, ie:
auto fileSize = m_file.tellg();
It will ensure that you don't use the wrong type and avoid implicit casts that may end up in losing info (like casting from a larger type to a smaller one). Plus you don't have to bother with the actual type (which can be cumbersome to type, and that you may get wrong).
Before C++11
I believe the correct thing to do is this:
std::fstream::pos_type fileSize = m_file.tellg();
If you have C++11
then you can do this:
auto fileSize = m_file.tellg();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.