C ++从二进制文件写入和读取双精度 [英] C++ writing and reading doubles from a binary file

查看:500
本文介绍了C ++从二进制文件写入和读取双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为需要太多RAM的程序执行磁盘I / O操作。
我使用双精度矩阵,并认为将它们写入磁盘作为字节是最快的方式(我需要保留双精度)。

I want to perform disk I/O operations for a program that takes too much RAM. I use matrices of doubles and think writing them to disk as bytes is the fastest way (I need to preserve the double precision).

如何做

我发现这个代码(这里),但作者说它不可移植...

I found this code (here) but the author says it's not portable...

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;

    ofstream ofs( "atest.txt", ios::binary );

    if ( ofs ) {
        double pi = 3.14;

        ofs.write( reinterpret_cast<char*>( &pi ), sizeof pi );
        // Close the file to unlock it
        ofs.close();

        // Use a new object so we don't have to worry
        // about error states in the old object
        ifstream ifs( "atest.txt", ios::binary );
        double read;

        if ( ifs ) {
            ifs.read( reinterpret_cast<char*>( &read ), sizeof read );
            cout << read << '\n';
        }
    }

    return 0;
}


推荐答案


如何使用可移植性?

How to do it with portability?

有不同的可移植性定义/级别。如果你所做的只是将它们写在一台机器上并在同一台机器上读取,那么你所关心的唯一可移植性就是这个代码是否定义良好。 (它是。)

如果你想要在几个不同的平台上可移植地写,你需要写入 string 值,而不是二进制。

There are different definitions/levels of portability. If all you ever do is to write these on one machine and read it on the same one, the only portability you are concerned with is whether this code is well-defined. (It is.)
If you want to write portably across several different platforms, you need to write string values, rather than binary ones.

但是,请注意,您缺少正确的错误处理代码。它不检查文件是否可以打开并成功写入。

However, note that the code you have lacks proper error handling. It doesn't check whether the file could be opened and successfully written to.

这篇关于C ++从二进制文件写入和读取双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆