相關函數介紹
在我們的C語言中讀寫二進制文件一般使用的fread、fwrite全局函數,當然也可以使用更底層的read和write函數。在我們的C++中 通過ofstream 和 ifstream 對象 讀寫文件更加的方便了。對二進制文件的讀寫 主要使用 ofstream::write,ifstream::read函數。如果對文件讀寫方向感不強,記不住的 ,記住4個字就行了。讀入寫出。這個4個字是針對 程序或者說是內存!往內存里面讀數據 -> read ,往磁盤里面寫數據->write。這樣永遠就會忘了。還有一些其他的函數,都比較簡單。感覺用起來很方便。
這里普及下序列化和反序列化。
序列化: 將數據結構或對象轉換成二進制串的過程。
反序列化:將在序列化過程中所生成的二進制串轉換成數據結構或者對象的過程。
下面就用相關函數實現普通的字符文件操作 和 二進制文件操作。代碼注釋很詳細
普通文件操作
-
#define _CRT_SECURE_NO_WARNINGS
-
#include <iostream>
-
#include <fstream>
-
using
namespace
std;
-
-
//寫文件
-
void WriteFile()
-
{
-
ofstream file("./text.txt",ios::out);
-
if (!file.is_open())
-
{
-
cout <<
"文件打開失敗" <<
endl;
-
return;
-
}
-
file <<
"姓名:laymond" <<
endl;
-
file <<
"年齡:18" <<
endl;
-
file.close();
-
return;
-
}
-
//讀文件
-
void ReadFile()
-
{
-
ifstream file("./text.txt", ios::in);
-
if (!file.is_open())
-
{
-
cout <<
"文件打開失敗" <<
endl;
-
return;
-
}
-
char temp[
1024] = {
0 };
-
//讀取文件3種方式
-
//1、read file.eof() 作為判斷條件 會慢一拍
-
while (file >> temp)
-
//while (!file.eof())
-
{
-
//file.read(temp, 1024); //這樣會讀取到\n
-
//cout << temp
-
-
// >>按行讀取,不會讀換行符
-
cout << temp <<
endl;
-
}
-
-
//2、get 一個一個字符的讀取
-
//char c;
-
//while ( (c=file.get()) != EOF )
-
//{
-
// cout << c;
-
//}
-
-
//3、一行一樣讀取 getline 會把\n 舍棄掉....
-
//while (file.getline(temp,1024))
-
//{
-
// cout << temp << endl;
-
//}
-
file.close();
-
}
二進制文件操作(序列化和反序列化)
接上面代碼哈,是寫在同一個文件中的。
-
class Person
-
{
-
public:
-
Person(
char* name,
int age)
-
{
-
strcpy(
this->name, name);
-
this->age = age;
-
}
-
void showInfo()
-
{
-
cout << name <<
" " << age <<
endl;
-
}
-
public:
-
char name[
10]{
0 };
-
int age =
0;
-
};
-
//二進制文件 進行寫
-
void WriteBinaryFile()
-
{
-
ofstream file("./binary.txt",ios::out | ios::binary );
-
if (!file.is_open())
-
{
-
cout <<
"文件打開失敗" <<
endl;
-
}
-
Person p1("Lay1", 11);
-
Person p2("Lay2", 2);
-
Person p3("Lay3", 151);
-
Person p4("Lay4", 5);
-
Person p5("Lay5", 9);
-
file.write((
char*)&p1,
sizeof(p1));
-
file.write((
char*)&p2,
sizeof(p2));
-
file.write((
char*)&p3,
sizeof(p3));
-
file.write((
char*)&p4,
sizeof(p4));
-
file.write((
char*)&p5,
sizeof(p5));
-
-
file.close();
-
}
-
//二進制文件 進行讀
-
void ReadBinaryFile()
-
{
-
ifstream file("./binary.txt", ios::in | ios::binary);
-
if (!file.is_open())
-
{
-
cout <<
"文件打開失敗" <<
endl;
-
}
-
//開辟一塊空間 存放讀取的數據
-
char* temp =
new
char[
sizeof(Person)];
-
//或者 Person p;開辟的空間肯定合適
-
-
//將數據讀入的 temp對應的空間
-
while (file.read(temp,
sizeof(Person)))
-
{
-
Person p = *(Person*)(temp);
-
p.showInfo();
-
}
-
file.close();
-
}
-
-
int main(int argc, char *argv[])
-
{
-
//讀寫 字符文件
-
//WriteFile();
-
//ReadFile();
-
-
//讀寫 二進制文件
-
//WriteBinaryFile();
-
ReadBinaryFile();
-
-
return EXIT_SUCCESS;
-
}