If I need to read int from ifstream
int myInt = 0; fileStream.read(reinterpret_cast<char*>(&myInt), sizeof(int)); is using reinterpret_cast<char*> correct way to accomplish that?
is using reinterpret_cast correct way to accomplish that?
Yes. Prefer c++ style casts, instead of c style casts.
As suggested in comments, a better way to use the read method function is :
int myInt = 0; fileStream.read(reinterpret_cast<char*>(&myInt), sizeof(myInt));
sizeof myIntto not repeat the type, and to be safe if you later to decide to change the type to e.g.longwhich might be a different size.sizeof myIntints fromifstreamas the question itself seems to indicate or is it how to cast frominttochar*as the title suggests?int*tochar*in order to read an object representation of anintfrom anifstreamdirectly into anint. You could avoid reading directly, and thus avoid the cast, by doing something likechar tmp[sizeof myInt]; filestream.read(tmp, sizeof myInt); std::memcpy(&myInt, &tmp, sizeof myInt);. But it's fairly pointless to write that code solely in order to make this question into two questions ;-)