C++写入和读取从二进制文件加倍

And*_*ndy 3 c++ io portability binaryfiles double-precision

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

如何做到便携?

我发现这个代码(这里),但作者说它不便携......

#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;
}
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 5

如何做到便携?

可移植性有不同的定义/级别.如果您所做的只是在一台机器上编写这些并在同一台机器上读取它,那么您唯一关心的可移植性是这个代码是否定义明确.(它是.)
如果你想在几个不同的平台上进行便携式编写,你需要编写字符串值,而不是二进制值.

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