• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C/C++中二进制文件&顺序读写详解及其作用介绍

c++ 搞代码 4年前 (2022-01-06) 55次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C/C++中二进制文件&顺序读写详解及其作用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

概述

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

二进制 vs ASCII

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

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

二进制写入

 #include  #include  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 写入文件.

 #include<strong style="color:transparent">来源gaodai#ma#com搞@代~码网</strong>  #include  using namespace std; int main() { int x = 12345; ofstream outfile("ASCII.txt"); outfile << x << endl;  // 写入 outfile.close();  // 释放 return 0; } 

输出结果:

read 和 write 读写二进制文件

打开方式:

 ofstream a("file1.dat", ios::out | ios::binary); ifstream b("file2.dat",ios::in | ios::binary); 

文件读写方式:

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

例子:

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

 a.write(p1,50) 

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

 b.read(p2,30) 

案例一

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

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

案例二

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

 #include  #include  #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++中二进制文件&顺序读写详解及其作用介绍的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C/C++中二进制文件&顺序读写详解及其作用介绍

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址