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)
具体的原因留给读者自己思考
写入文件的是二进制,用记事本无法正确显示,可以用支持二进制的编辑器打开,(如图)
相关文章推荐
- C++读写二进制文件
- C++:读写二进制文件到float数组
- C++读写二进制文件
- c/c++ 二进制文件读写
- C/C++ 二进制 追加读写文件
- C++读写二进制文件
- C++ 二进制文件读写
- C++语言基础 例程 二进制文件及其顺序读写
- (转载)用C++中STL提供的fstream和stream_iterator读写二进制文件
- C++二进制文件读写
- C++下按二进制读写文件
- c++读写二进制文件
- C/C++:文本文件和二进制文件的读写
- C++读写文件(二进制)
- 基于C++实现文件的明文和二进制读写
- C++读写二进制文件
- C++读写二进制文件
- C/C++读写文本文件、二进制文件
- C++读写二进制文件
- C++读写二进制文件