前面學習了對文本文件的讀寫操作,有了這個基礎,我們來學習下,C++對二進制文件的讀寫操作。因爲是二進制,所以不管是讀還是寫文件,其中打開方式要指定爲iso::binary。
1.寫二進制文件
二進制方式寫文件主要利用流對象調用成員函數write()
函數原型:ostream& write(const char * buffer, int len);
參數解釋:字符指針buffer指向內存中一段存儲空間,len是讀寫的字節數
來看一個代碼例子
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
class Person
{
public:
string m_Name;
int m_Age;
};
void test01()
{
ofstream ofs;
ofs.open("test1.txt", ios::out | ios::binary);
Person p = {"Anthony", 28};
ofs.write( (const char *)&p, sizeof(p));
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
運行之後,在代碼同目錄下有一個test1.txt
一般二進制內容打開就是亂碼,接下來我們學習讀二進制文件,讀出來然後打印到控制檯內容就清楚了。
2.讀二進制文件
二進制方式讀文件主要利用流對象調用成員函數read()
函數原型:istream& read(char *buffer, int len);
參數解釋:字符指針buffer指向內存中一段內存空間,len是讀寫的字節數
直接讀取上面代碼產生的test1.txt文件
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
class Person
{
public:
string m_Name;
int m_Age;
};
void test01()
{
ifstream ifs; //把二進制文件內容Input到我們程序,所以需要使用input file stream
ifs.open("test1.txt", ios::in | ios::binary);
if(!ifs.is_open())
{
cout << "文件打開失敗!" << endl;
return;
}
//讀出來
Person p;
ifs.read((char *)&p, sizeof(Person));
cout << "姓名:" << p.m_Name << endl;
cout << "年齡:" << p.m_Age << endl;
ifs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
運行控制檯輸出
總結:
二進制讀文件,使用流對象的read()函數,寫文件,使用流對象的write方法,其中讀寫方法的兩個參數的含義是一樣的,第一個參數指針這塊,需要強制轉換成函數的類型。