zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++文件数组二进制 读写 double
2023-09-14 09:09:30 时间
在以下的代码中,我们将写入一个double数组到1.txt中,并且读取出来。
主要采用了fstream这个库,代码如下:

link

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