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

在以下的代码中,我们将写入一个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)

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


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

这里写图片描述
这里写图片描述

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常抱歉,我理解有误。下面是包含 `fopen` 函数的读写文本文件二进制文件的示例代码: 1. 读写文本文件: ```c++ #include <stdio.h> int main() { FILE* fp; char buf[512]; // 以只读方式打开文件 fp = fopen("example.txt", "r"); if (!fp) { printf("Failed to open file!\n"); return 0; } // 读取文件内容 while (fgets(buf, sizeof(buf), fp)) { printf("%s", buf); } // 关闭文件 fclose(fp); // 以只写方式打开文件 fp = fopen("example.txt", "a"); if (!fp) { printf("Failed to open file!\n"); return 0; } // 写入文件内容 fprintf(fp, "This is a new line.\n"); // 关闭文件 fclose(fp); return 0; } ``` 在以上示例代码中,`fopen` 函数用于打开文件,`fgets` 函数用于读取文件内容,`fprintf` 函数用于写入文件内容,`fclose` 函数用于关闭文件。 2. 读写二进制文件: ```c++ #include <stdio.h> struct student { int id; char name[20]; double score; }; int main() { FILE* fp; student s; // 以二进制读方式打开文件 fp = fopen("example.bin", "rb"); if (!fp) { printf("Failed to open file!\n"); return 0; } // 读取文件内容 while (fread(&s, sizeof(s), 1, fp)) { printf("%d %s %lf\n", s.id, s.name, s.score); } // 关闭文件 fclose(fp); // 以二进制写方式打开文件 fp = fopen("example.bin", "ab"); if (!fp) { printf("Failed to open file!\n"); return 0; } // 写入文件内容 student s1 = {1, "Tom", 90.5}; student s2 = {2, "Jerry", 85.5}; fwrite(&s1, sizeof(s1), 1, fp); fwrite(&s2, sizeof(s2), 1, fp); // 关闭文件 fclose(fp); return 0; } ``` 在以上示例代码中,`fopen` 函数用于打开文件,`fread` 函数用于读取文件内容,`fwrite` 函数用于写入文件内容,`fclose` 函数用于关闭文件。注意,二进制文件需要以二进制方式打开,因此在文件打开模式中需要加上 "b" 标识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值