前言
大家好久不见,今天一起来学习c++中的IO流。
输入输出库
这两张架构图略显复杂,这里给出一张比较清楚的IO流架构图:
也就是说,我们平时使用的诸如cin、cout、cerr、clog都是来自
<iostream>
这个头文件下的,他们分别是
<istream>
头文件下的istream和ostream的实例对象。
<istream>
头文件里的iostream继承了istream和ostream两个类,因此在
<fstream>
和
<sstream>
类里的fstream和sstream都兼具对应的io功能。
文件读写
这里顺便说明一下:友元的实现是编译器通过特殊机制授权让这个函数能拿到类的成员的,而不是通过this指针拿到的,而istream其实就是basic_istream<char, char_traits<char>>的一个别名.
class Date
{
//友元关系不会被继承
friend istream& operator >>(istream& in, Date& date);
friend ostream& operator <<(ostream& out, const Date& date);
public:
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{}
operator bool()
{
if (_year == 0)
return false;
return true;
}
private:
int _year;
int _month;
int _day;
};
//输入重定向
//
//decltype(cin)& operator >>(decltype(cin)& no,const Date& date)
//basic_istream<char, struct std::char_traits<char>>& operator >>(decltype(cin)& no, const Date& date)
//basic_istream<char>& operator >>(decltype(cin)& no, const Date& date)
istream& operator >>(istream& in, Date& date)
{
//cout << ">> ok" << endl;
//cout << typeid(cin).name() << endl;
in >> date._year >> date._month >> date._day;
return in;
}
//输出重定向
ostream& operator <<(ostream& out, const Date& date)
{
out << date._year << " " << date._month << " " << date._day;
return out;
}
#include <fstream>
struct ServerInfo
{
//string _address;
char _address[32];
int _port;
Date _date;
};
class ConfigManager
{
public:
ConfigManager(string filename) : _filename(filename)
{
}
//二进制读写
void ReadBin(ServerInfo& info)
{
ifstream ifs(_filename, istream::in | istream::binary);
ifs.read((char*)&info, sizeof(info));
}
void WriteBin(const ServerInfo& info)
{
ofstream ofs(_filename, ofstream::out | ofstream::binary);
ofs.write((char*)&info, sizeof(info));
//必然不能写入string,string的内容是new出来的,这里只把指针存好了
}
//文本读写
void ReadText(ServerInfo& info)
{
ifstream ifs(_filename);
ifs >> info._address;
ifs >> info._port;
ifs >> info._date;
}
void WriteText(const ServerInfo& info)
{
ofstream ofs(_filename);
ofs << info._address << endl;
ofs << info._port << endl;
ofs << info._date << endl;
}
private:
string _filename;
};
序列化与反序列化
// 序列化和反序列化
#include <sstream>
struct ChatInfo
{
string _name; // 名字
int _id; // id
Date _date; // 时间
string _msg; // 聊天信息
};
ostream& operator<<(ostream& out, ChatInfo& info)
{
cout << info._name << info._id << info._date << info._msg << endl;
return out;
}
int main()
{
ChatInfo winfo = { "丁真", 135246, { 2022, 7, 14 }, "你好我是雪豹" };
stringstream oss;
oss << winfo._name << " ";
oss << winfo._id << " ";
oss << winfo._date << " ";
oss << winfo._msg;
string str = oss.str();
stringstream iss(str);
ChatInfo rinfo;
iss >> rinfo._name;
iss >> rinfo._id;
iss >> rinfo._date;
iss >> rinfo._msg;
cout << rinfo << endl;
return 0;
}
结语
到这里,就是IO流的全部内容了,感谢观看,我们下次再见~
版权声明:本文为m0_73209194原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。