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?

5
  • 1
    This might be of assistance: stackoverflow.com/questions/4748232/reinterpret-cast :) Commented Dec 20, 2011 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. Commented Dec 20, 2011 at 13:49
  • 1
    Thanks. Sounds like a good idea to use sizeof myInt Commented Dec 20, 2011 at 13:55
  • I am a bit confused on what the actual question is. Is it how to read ints from ifstream as the question itself seems to indicate or is it how to cast from int to char* as the title suggests? Commented Dec 20, 2011 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 ;-) Commented Dec 20, 2011 at 15:15

1 Answer 1

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)); 
Sign up to request clarification or add additional context in comments.

2 Comments

I disagree with the answer (not the comment about c++ and c style casts), see Jon's answer below.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.