473,473 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

reinterpret_cast ? bad? good?


I want to save tables of integers to files.
One way to write the cells as fixed size in the file, is to use
reinterpret_cast.
Is that a bad choice, good choice? I remember once before I posted a program
using it, and some suggested that I might get errors using it.
are there any other ways to write the cells as fixed size in the file?
(knowing the cells will only contain integers).
here is how I plan to do it (without much caring about all the details),

int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));

thx for any feedback.

--
Quotes from The Weather Man:
Robert Spritz: Do you know that the harder thing to do, and the right thing
to do, are usually the same thing? "Easy" doesn't enter into grown-up
life... to get anything of value, you have to sacrifice.
Apr 11 '06 #1
11 3750

Someonekicked wrote:
I want to save tables of integers to files.
One way to write the cells as fixed size in the file, is to use
reinterpret_cast.
Is that a bad choice, good choice? I remember once before I posted a program
using it, and some suggested that I might get errors using it.
are there any other ways to write the cells as fixed size in the file?
(knowing the cells will only contain integers).
here is how I plan to do it (without much caring about all the details),

int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));


reinterpret_cast is bad. However, is it sometimes necessary? Well,
you have just shown one area where it is. There isn't really any other
way to output to a binary file than what you are doing above. You have
to 'translate' you data to bytes so somewhere down the line you have to
do a reinterpret cast to bitwise cast your data into byte delimited
chunks...chars. This act of course kills portability, but the very act
of writing binary data to a file is itself not portable...you can't
take that file to any computer and expect it to work without taking
great care to translate between systems.

reinterpret_cast indicates non-portable code any time it is used. As
such, any time you do use it you need to ask yourself if what you are
doing is in fact correct. The only cast that raises more flags is a
const_cast.

Apr 11 '06 #2
you can make your IO more portable by converting to network endian
before writing (and to host enadian after reading) - the same way you
would do when sending through a socket.

Apr 11 '06 #3
>> here is how I plan to do it (without much caring about all the details),

int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));


reinterpret_cast is bad. However, is it sometimes necessary? Well,
you have just shown one area where it is. There isn't really any other
way to output to a binary file than what you are doing above. You have
to 'translate' you data to bytes so somewhere down the line you have to
do a reinterpret cast to bitwise cast your data into byte delimited
chunks...chars. This act of course kills portability, but the very act
of writing binary data to a file is itself not portable...you can't
take that file to any computer and expect it to work without taking
great care to translate between systems.

Agree.

That said, the fact that the integer is reinterpret_casted to a char*
is better hidden from the user as it is indeed an implementation technique.

One way to do this is to use overloaded functions:

void write_data(const File_stream& outFile, int target)
{
char* p = reinterpret_cast<char*>(*target);
outFile.write(p, sizeof(int));
}

This way the user can simply use it as the following:

int i = 42;
File_stream f("myfile");
write_data(f, i);

If somehow you have better alternative than the reinterpret_cast there
is only one place you need to change, instead of inspecting the whole
project.

Regards,
Ben
Apr 11 '06 #4
yu*****@gmail.com wrote:
you can make your IO more portable by converting to network endian
before writing (and to host enadian after reading) - the same way you
would do when sending through a socket.


However, even that assumes that the sizes of the types being written to
disk are the same between the two platforms. It would be better to say
that you must define a "canonical form" for anything you write to disk.
That definition may be: ints will be written as 4 bytes in
network-byte-order. However, that does limit your file format to 4 byte
integers.....
Apr 11 '06 #5
Someonekicked wrote:
int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));


You are asking whether binary files are good. They are bad. Write text and
read text. The Boost Serialization library has a good example how; so does
the tinyxml project.

Don't write a binary file "because it's faster". The tiny speed hit of
formatting and deformatting strings is more than compensated by your rapid
development.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 11 '06 #6
yuvalif wrote:
you can make your IO more portable by converting to network endian
before writing (and to host enadian after reading) - the same way you
would do when sending through a socket.


That's another reason to write text, not binary.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 11 '06 #7
Phlip <ph*******@gmail.com> wrote:
Someonekicked wrote:
int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));


You are asking whether binary files are good. They are bad. Write
text and read text. The Boost Serialization library has a good
example how; so does the tinyxml project.

Don't write a binary file "because it's faster". The tiny speed hit of
formatting and deformatting strings is more than compensated by your
rapid development.


All generalizations are false ;)

No seriously, consider a 3D file format that contains vertex data.
With todays high-poly models, the speed hit caused by parsing the file
will be enormous.

I agree that for settings or alike, formatting and deformatting is
no big deal.

So the answer really depends on what the OP is doing.

regards
--
jb

(reply address in rot13, unscramble first)
Apr 11 '06 #8
Jakob Bieling wrote:
All generalizations are false ;)


So are all made-up statistics.

For example, 51% of the posts here are of the format "I'm trying to speed my
code up without profiling it to find the real statistics, or generally
finding a need. How do I do blah-blah-blah that's heinously complicated?"

Is there a FAQ citation for the "premature optimization is the root of all
evil" generalization I could link out to? Answering such posts is difficult
without triggering another "premature optimization" thread...

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 11 '06 #9
Phlip wrote:
Jakob Bieling wrote:

All generalizations are false ;)

So are all made-up statistics.

For example, 51% of the posts here are of the format "I'm trying to speed my
code up without profiling it to find the real statistics, or generally
finding a need. How do I do blah-blah-blah that's heinously complicated?"

Is there a FAQ citation for the "premature optimization is the root of all
evil" generalization I could link out to? Answering such posts is difficult
without triggering another "premature optimization" thread...

I think you missed the key point:

"So the answer really depends on what the OP is doing."

--
Ian Collins.
Apr 11 '06 #10
it is a simple project for my DB class.
There are two tables of integers (put in two files), and we have to do a
hash join (equijoin), using buckets (buckets must be files too).
The tables will only contain integers.
so I want to put the second table (file) into buckets, then do the join.
so I was thinking of making the cells in the buckets files fixed size, so I
only read the entry in the column I am interesed it, rather than reading the
whole row everytime. Then if that entry satisfy the join condition, then I
can read the whole row.
The program will be supposably tested with millions of data.

--
Quotes from The Weather Man:
Robert Spritz: Do you know that the harder thing to do, and the right thing
to do, are usually the same thing? "Easy" doesn't enter into grown-up
life... to get anything of value, you have to sacrifice.
"Someonekicked" <so***********@comcast.net> wrote in message
news:Kc********************@comcast.com...

I want to save tables of integers to files.
One way to write the cells as fixed size in the file, is to use
reinterpret_cast.
Is that a bad choice, good choice? I remember once before I posted a
program using it, and some suggested that I might get errors using it.
are there any other ways to write the cells as fixed size in the file?
(knowing the cells will only contain integers).
here is how I plan to do it (without much caring about all the details),

int cell = 20;
outFile.write(reinterpret_cast<const char *> (&cell),sizeof(cell));

thx for any feedback.

--
Quotes from The Weather Man:
Robert Spritz: Do you know that the harder thing to do, and the right
thing
to do, are usually the same thing? "Easy" doesn't enter into grown-up
life... to get anything of value, you have to sacrifice.

Apr 12 '06 #11

benben wrote:
One way to do this is to use overloaded functions:

void write_data(const File_stream& outFile, int target)
{
char* p = reinterpret_cast<char*>(*target);
outFile.write(p, sizeof(int));
}

This way the user can simply use it as the following:

int i = 42;
File_stream f("myfile");
write_data(f, i);


What about this? I think it's more generic:

template<class T>
bool write_data( const File_stream& outFile, T& target )
{
std::stringstream ss;
std::string str;
if( !(ss << target ) || ss.fail() || !(ss >> str) )
{
return false;
}

//now write str to the outFile

return true;
}

It can be overloaded for T as std::string

Apr 12 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Suzanne Vogel | last post by:
I'd like to convert a double to a binary representation. I can use the "&" bit operation with a bit mask to convert *non* float types to binary representations, but I can't use "&" on doubles. ...
18
by: johny smith | last post by:
Can someone please give me some good reference site/information for understanding when and why I would use 1.) const_cast Don't know why you would do this? 2.) reinterpret_cast. I have used...
32
by: KK | last post by:
Hello all, I have a unsigned char buffer 'buffer' and I need to convert the first 12 bytes of it into a string. Below is a code that should work, however, how can I avoid reinterpret_cast...
2
by: Taran | last post by:
Hi All, I was trying some code which essentially does what the function 'func' here does. To simplify the things and make a consise post I have created a dummy app to show my problem. The issue...
7
by: Peter | last post by:
I never used reinterpret_cast -- probably because I don't know what it means. Can somebody enlighten me? I looked into Stroustrup's "The annoted C++ reference manual" -- but this was no help....
27
by: Noah Roberts | last post by:
What steps do people take to make sure that when dealing with C API callback functions that you do the appropriate reinterpret_cast<>? For instance, today I ran into a situation in which the wrong...
2
by: jasm | last post by:
hello everybody! I have used reinterpret_cast for interpret a class object as a char*. This is the object: template<class T> class Coordinates { public: T *x; T *y;
2
by: ciccio | last post by:
Hi, I was wondering what the main reason is why reinterpret_cast fails to work as expected when using optimizations. Here is the simple example code which fail to give the correct result when...
15
by: saurabh | last post by:
I am trying to understand reinterpret_cast,here is what i tried, #include<iostream> #include<cstdio> using namespace std; int main() { int x=1; int* y=&x;
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.