C/C++中二進(jìn)制文件&順序讀寫詳解及其作用介紹
概述
二進(jìn)制文件不同于文本文件, 它可以用于任何類型的文件 (包括文本文件).

二進(jìn)制 vs ASCII
對于數(shù)值數(shù)據(jù), ASCII 形式與二進(jìn)制形式不同. ASCII 文件直觀, 便于閱讀, 但一般占存儲空間較多, 而且需要花時間轉(zhuǎn)換. 二進(jìn)制文件是計(jì)算機(jī)的內(nèi)部形式, 節(jié)省空間且不需要轉(zhuǎn)換, 但不能直觀顯示.
對于字符信息, 在內(nèi)存中是以 ASCII 代碼形式存放, 無論用 ASCII 文件輸出還是用二進(jìn)制文件輸出, 形式是一樣的.
二進(jìn)制寫入
#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;
}
輸出結(jié)果:

ASCII 寫入
將 int x = 12345 寫入文件.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int x = 12345;
ofstream outfile("ASCII.txt");
outfile << x << endl; // 寫入
outfile.close(); // 釋放
return 0;
}
輸出結(jié)果:

read 和 write 讀寫二進(jìn)制文件
打開方式:
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 指向內(nèi)存中一段存儲空間
- int len 是讀寫的字節(jié)數(shù)
例子:
將 p1 指向的空間中 50 個字節(jié)存入文件對象 a:
a.write(p1,50)
從文件對象 b 讀出 30 個字節(jié), 存址指向空間:
b.read(p2,30)
案例一
將數(shù)據(jù)以二進(jìn)制的形式存放在磁盤中.
#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 << "任務(wù)完成, 請查看文件" << endl;
outfile.close();
return 0;
}
案例二
將二進(jìn)制文件中的數(shù)據(jù)讀入內(nèi)存.
#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); // 退出程序
}
// 讀取數(shù)據(jù)
for (int i = 0; i < 2; ++i) {
infile.read((char*)&stud[i], sizeof(stud[i]));
}
infile.close();
// 顯示數(shù)據(jù)
for (int i = 0; i < 2; ++i) {
stud[i].display();
}
return 0;
}
到此這篇關(guān)于C/C++中二進(jìn)制文件&順序讀寫詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++二進(jìn)制&順序讀寫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
OpenGL實(shí)現(xiàn)鼠標(biāo)移動方塊
這篇文章主要為大家詳細(xì)介紹了OpenGL實(shí)現(xiàn)鼠標(biāo)移動方塊,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-08-08
C語言實(shí)現(xiàn)手寫字符串處理工具的示例代碼
這篇文章主要為大家詳細(xì)介紹了利用C語言實(shí)現(xiàn)手寫字符串處理工具的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,需要的可以參考一下2022-09-09
C++基礎(chǔ)入門篇之強(qiáng)制轉(zhuǎn)換
這篇文章主要給大家介紹了關(guān)于C++基礎(chǔ)入門篇之強(qiáng)制轉(zhuǎn)換的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

