10

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?

dextrey
  • 815
  • 7
  • 9
  • 1
    This might be of assistance: http://stackoverflow.com/questions/4748232/reinterpret-cast :) – Victor Parmar Dec 20 '11 at 13:48
  • 11
    Consider using `sizeof myInt` to not repeat the type, and to be safe if you later to decide to change the type to e.g. `long` which might be a different size. – unwind Dec 20 '11 at 13:49
  • 1
    Thanks. Sounds like a good idea to use `sizeof myInt` – dextrey Dec 20 '11 at 13:55
  • I am a bit confused on what the actual question is. Is it how to read `int`s from `ifstream` as the question itself seems to indicate or is it how to cast from `int` to `char*` as the title suggests? – hmjd Dec 20 '11 at 13:57
  • @hmjd: both. It is necessary to cast `int*` to `char*` in order to read an object representation of an `int` from an `ifstream` directly into an `int`. You could avoid reading directly, and thus avoid the cast, by doing something like `char 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 ;-) – Steve Jessop Dec 20 '11 at 15:15

1 Answers1

15

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));
BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • I disagree with the answer (not the comment about c++ and c style casts), see Jon's answer below. – Walter Dec 20 '11 at 14:19
  • @Walter There is a down vote on the left. However, Jon's answer is not going to work if it is being read from a binary file. – BЈовић Dec 20 '11 at 14:25