简体   繁体   中英

Reading double from binary files

需要格式化,编辑将花费一些时间。

Reading using fin >> d and using fin.read does different things. As fin >> d works it seems you have a file where the string representation of a double is written. Using fin.read suggests that your file is written in binary which it seems it is not. Also you should better use sizeof(double) instead of the hard coded constant 8 .

The problem is that you missunderstood the semantic of std::ifstream::read function. According to C++ reference:

Note: This doc is for std::istream but applies to ifstream

std::istream::operator>>()

This operator (>>) applied to an input stream is known as extraction operator. It is overloaded as a member function for:

arithmetic types

Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val . Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to false). Then (if good), it calls num_get::get (using the stream's selected locale) to perform both the extraction and the parsing operations, adjusting the stream's internal state flags accordingly. Finally, it destroys the sentry object before returning.

stream buffers and manipulators .

while for std::istream::read :

This function simply copies a block of data, without checking its contents nor appending a null character at the end.

So, when you do:

double d;
...
fin >> d;

You're storing a double into a double var. But ...

if you do:

double d;
...
fin.read((char*)&d, ...);

you are telling to c++: Ok here (&d) I have an address, I want you trate it as it was char* (the cast). And the function do what you want to do. But as you see in doc, the function will put in &d a block of data that has nothing to do with the walue you're expecting.

That's why operator>> works while read doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM