您的位置:首页 > 编程语言 > C语言/C++

C++:读写二进制文件到double数组

2018-02-04 21:04 701 查看

在以下的代码中,我们将写入一个double数组到1.txt中,并且读取出来。

主要采用了fstream这个库,代码如下:

#include <math.h>
#include <fstream>
#include <iostream>
int main(){
const int length = 100;
double f1[length] ;
for (int i = 0; i < length; i++)
{
f1[i] = i + i / 1000.0;
}
std::ofstream  ofs("1.txt", std::ios::binary | std::ios::out);
ofs.write((const char*)f1, sizeof(double) * length);
ofs.close();

double* f2 = new double[length];
std::ifstream ifs("1.txt", std::ios::binary | std::ios::in);
ifs.read((char*)f2, sizeof(double) * length);
ifs.close();

for (int i = 0; i < length; i++)
{
std::cout<<f2[i]<<std::endl;
}
return 0;
}


代码解析:

我们初始化了一个长度为12的double数组f1,如下

0

1.001

2.002

3.003

4.004

5.005

6.006

7.007

8.008

9.009

10.01

11.011

12.012

13.013

14.014

15.015

16.016

17.017

18.018

19.019

20.02

……

……

80.08

81.081

82.082

83.083

84.084

85.085

86.086

87.087

88.088

89.089

90.09

91.091

92.092

93.093

94.094

95.095

96.096

97.097

98.098

99.099

通过以下的代码写入1.txt

ofs.write((const char*)f1, sizeof(double) * length);


通过以下的代码从1.txt写入到f2数组

ofs.write((const char*)f1, sizeof(double) * length);


需要注意的是写入和读出的长度为 【double数组长度】*sizeof(double)

具体的原因留给读者自己思考

写入文件的是二进制,用记事本无法正确显示,可以用支持二进制的编辑器打开,(如图)



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: