How to output array of doubles to hard drive?

c++

Solution

Hey... so you want to do it in a single write/read, well its not too hard, the following code should work fine, maybe need some extra error checking but the trial case was successful:

#include <string>
#include <fstream>
#include <iostream>

bool saveArray( const double* pdata, size_t length, const std::string& file_path )
{
    std::ofstream os(file_path.c_str(), std::ios::binary | std::ios::out);
    if ( !os.is_open() )
        return false;
    os.write(reinterpret_cast<const char*>(pdata), std::streamsize(length*sizeof(double)));
    os.close();
    return true;
}

bool loadArray( double* pdata, size_t length, const std::string& file_path)
{
    std::ifstream is(file_path.c_str(), std::ios::binary | std::ios::in);
    if ( !is.is_open() )
        return false;
    is.read(reinterpret_cast<char*>(pdata), std::streamsize(length*sizeof(double)));
    is.close();
    return true;
}

int main()
{
    double* pDbl = new double[1000];
    int i;
    for (i=0 ; i<1000 ; i++)
        pDbl[i] = double(rand());

    saveArray(pDbl,1000,"test.txt");

    double* pDblFromFile = new double[1000];
    loadArray(pDblFromFile, 1000, "test.txt");

    for (i=0 ; i<1000 ; i++)
    {
        if ( pDbl[i] != pDblFromFile[i] )
        {
            std::cout << "error, loaded data not the same!\n";
            break;
        }
    }
    if ( i==1000 )
        std::cout << "success!\n";

    delete [] pDbl;
    delete [] pDblFromFile;

    return 0;
}

Just make sure you allocate appropriate buffers! But thats a whole nother topic.

Problem

I would like to know how to output an array of doubles to the hard drive. edit: for further clarification. I would like to output it to a file on the hard drive (I/O functions). Preferably in a file format that can be quickly translated back into an array of doubles in another program. It would also be nice if it was stored in a standard 4 byte configuration so that i can look at it through a hex viewer and see the actual values.

Original source