如何输出双硬盘阵列? [英] How to output array of doubles to hard drive?

查看:109
本文介绍了如何输出双硬盘阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何输出一个双精度数组到硬盘驱动器。

I would like to know how to output an array of doubles to the hard drive.

编辑:

我想把它输出到硬盘驱动器上的文件(I / O功能)。优选地,以可以在另一程序中快速转换回双重数组的文件格式。如果它存储在一个标准的4字节配置,所以我可以看看它通过十六进制查看器,并看到实际的值,这也将是很好。

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.

推荐答案

嘿...所以你想要在一个单一的写/读,它不是太难,以下代码应该工作正常,也许需要一些额外的错误检查,但试用案例成功:

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.

这篇关于如何输出双硬盘阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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