C/C++中二進制文件&順序讀寫詳解及其作用介紹
概述
二進制文件不同于文本文件, 它可以用于任何類型的文件 (包括文本文件).
二進制 vs ASCII
對于數(shù)值數(shù)據(jù), ASCII 形式與二進制形式不同. ASCII 文件直觀, 便于閱讀, 但一般占存儲空間較多, 而且需要花時間轉(zhuǎn)換. 二進制文件是計算機的內(nèi)部形式, 節(jié)省空間且不需要轉(zhuǎn)換, 但不能直觀顯示.
對于字符信息, 在內(nèi)存中是以 ASCII 代碼形式存放, 無論用 ASCII 文件輸出還是用二進制文件輸出, 形式是一樣的.
二進制寫入
#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 讀寫二進制文件
打開方式:
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ù)以二進制的形式存放在磁盤中.
#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; }
案例二
將二進制文件中的數(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++中二進制文件&順序讀寫詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++二進制&順序讀寫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!