相关函数介绍
在我们的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;
-
}