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

时间:2011-07-22 12:13:44

标签: c++ io portability binaryfiles double-precision

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

如何使用便携性?

我找到了这段代码(here),但作者说它不便携......

#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;
}

4 个答案:

答案 0 :(得分:5)

  

如何使用便携性?

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

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

答案 1 :(得分:2)

我认为只有在您写入文件并在另一台计算机上读取文件时才会出现可移植性问题。但是,由于ram限制,因为您说要读取/写入文件,所以我只能假设您一次只能在一台计算机上进行读/写操作。这应该有用。

答案 2 :(得分:1)

他可能一直指二进制表示,而不仅仅是sizeof。

C - Serialization of the floating point numbers (floats, doubles)

规范根本没有指定浮点数的二进制表示。 大多数编译器都遵循IEEE,因此如果您了解目标平台,则需要进行一些单元测试以确保您想要的行为。

答案 3 :(得分:0)

通常我用union访问字节。

union Data {
    double val;
    unsigned char str[sizeof(double)];
};

void saveToFile(double *values, int nvalues, const char *filename){
    int i;
    FILE *arq;
    Data num;

    arq=fopen(filename,"w");
    if (arq == NULL) {
        printf("Failed to open file \"%s\"\n", filename);
        exit(0);
    }

    for(i=0; i<nvalues; i++){
        num.val = values[i];
        fwrite (num.str , sizeof(char), sizeof(double), arq);    //ChunkSize
    }

    fclose(arq);
}

void loadFromFile(double *values, int nvalues, const char *filename){
    int i;
    FILE *arq;
    Data num;

    arq=fopen(filename,"r");
    if (arq == NULL) {
        printf("Failed to open file \"%s\"\n", filename);
        exit(0);
    }

    for(i=0; i<nvalues; i++){
        fread(num.str, sizeof(char), sizeof(double), arq);
        values[i] = num.val;
    }

    fclose(arq);
}