我是靠谱客的博主 负责皮卡丘,这篇文章主要介绍C/C++中二进制文件&顺序读写详解及其作用介绍,现在分享给大家,希望可以做个参考。

概述

二进制文件不同于文本文件, 它可以用于任何类型的文件 (包括文本文件).

二进制 vs ASCII

对于数值数据, ASCII 形式与二进制形式不同. ASCII 文件直观, 便于阅读, 但一般占存储空间较多, 而且需要花时间转换. 二进制文件是计算机的内部形式, 节省空间且不需要转换, 但不能直观显示.

对于字符信息, 在内存中是以 ASCII 代码形式存放, 无论用 ASCII 文件输出还是用二进制文件输出, 形式是一样的.

二进制写入

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream> #include <iostream> using namespace std; int main() { int x = 12345; ofstream outfile("binary.txt", ios::binary); outfile.write((char*)&x, 2); // 写入 outfile.close(); // 释放 return 0; }

输出结果:

ASCII 写入

将 int x = 12345 写入文件.

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream> #include <iostream> using namespace std; int main() { int x = 12345; ofstream outfile("ASCII.txt"); outfile << x << endl; // 写入 outfile.close(); // 释放 return 0; }

输出结果:

read 和 write 读写二进制文件

打开方式:

复制代码
1
2
ofstream a("file1.dat", ios::out | ios::binary); ifstream b("file2.dat",ios::in | ios::binary);

文件读写方式:

复制代码
1
2
istream& read(char *buffer,int len); ostream& write(const char * buffer,int len);
  • char *buffer 指向内存中一段存储空间
  • int len 是读写的字节数

例子:

将 p1 指向的空间中 50 个字节存入文件对象 a:

复制代码
1
a.write(p1,50)

从文件对象 b 读出 30 个字节, 存址指向空间:

复制代码
1
b.read(p2,30)

案例一

将数据以二进制的形式存放在磁盘中.

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream> #include <iostream> #include "Student.h" using namespace std; int main() { Student stud[2] = { {01, "Little White"}, {01, "Big White"} }; ofstream outfile("student.dat", ios::binary); if(!outfile){ cerr << "open error" << endl; exit(1); // 退出程序 } for (int i = 0; i < 2; ++i) { outfile.write((char*)&stud[i], sizeof(stud[i])); } cout << "任务完成, 请查看文件" << endl; outfile.close(); return 0; }

案例二

将二进制文件中的数据读入内存.

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <fstream> #include <iostream> #include "Student.h" using namespace std; int main() { Student stud[2]; ifstream infile("student.dat", ios::binary); if(!infile){ cerr << "open error" << endl; exit(1); // 退出程序 } // 读取数据 for (int i = 0; i < 2; ++i) { infile.read((char*)&stud[i], sizeof(stud[i])); } infile.close(); // 显示数据 for (int i = 0; i < 2; ++i) { stud[i].display(); } return 0; }

到此这篇关于C/C++中二进制文件&顺序读写详解及其作用介绍的文章就介绍到这了,更多相关C++二进制&顺序读写内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是负责皮卡丘最近收集整理的关于C/C++中二进制文件&顺序读写详解及其作用介绍的全部内容,更多相关C/C++中二进制文件&顺序读写详解及其作用介绍内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部