+ 12
Why we use reinterpret_cast, while reading from file in c++
17 Réponses
+ 13
There is no need to: binary files have no restrictions on what you can read/write:
#include <fstream>
#include <string>
using namespace std::literals;
int main(){
std::ofstream("terca.bin", std::ios::binary) << "\0\x1a\xff"s << 5.14;
}
Where you’re likely to be using reinterpret_cast is when you’re writing the object representation - the actual bytes of RAM used to represent an object in your program. For example, if you want to dump the double with value 5.14 as the 8 bytes it’s made of in memory, and not as the four bytes of its decimal text representation (like I did in the first example):
#include <fstream>
int main(){
double d = 5.14; std::ofstream("terca.bin", std::ios::binary).write( reinterpret_cast<char*>(&d), sizeof d);
}
This reinterpretation isn’t really about file I/O, it’s about obtaining the underlying bytes of an object.
+ 4
Because that's the only way to receive binary input from a file.
+ 3
Xander Lim reinterpret_cast<dest_ptr_t>(src_ptr) changes the type of src_ptr to dest_ptr_t without changing anything in the underlying data. In most cases, it's unsafe and you shouldn't use it.
+ 2
Because this actually is a reinterpret_cast, but hidden. Look here for more information: https://www.google.com/amp/s/embeddedartistry.com/blog/2017/2/28/c-casting-or-oh-no-we-broke-malloc%3fformat=amp
+ 2
Xander Lim Sometimes you need it, though.
+ 2
Raj kumar patel Please create a new thread. It will keep this thread on topic and it also helps yourself: More competent people will see the question.
+ 1
no its working correctly without using reinterpret_cast
+ 1
Binary input? Ok, how?
+ 1
this way.
while(fileHandler.read((char*)&obj, sizeof(obj))
{
obj.showData();
}
+ 1
Mohit the coder (M.S.D) Ok, I was unclear, but that's what I meant.
+ 1
sachin singh Tell you what?
+ 1
Hi
+ 1
OK. I thought u say I don't need it. now I understand sometimes I still need it.
+ 1
My xampp server is not working properly what can I do to fix it
0
what is this?
0
OK I won't use it.
0
Sometimes we need it