C++的IO流
1、C语言的输入输出
C语言用的输入输出方式是scanf()和printf()
scanf()是指从标准输入设备读取数据,将输入存放在变量中
printf()是指将指定的文字/字符输出到标准输出设备
输入输出缓冲区:
1、可以屏蔽掉低级IO,实现可移植的程序
2、可以使用这部分的内容实现“行”读取的行为
2、流的概念
2.1、流的概念
“流”即是流动的意思,是物质从一处向另一处流动的过程,是对一种有序连续且具有方向性的数据( 其单位可以是bit,byte,packet )的抽象描述。 C++流是指信息从外部输入设备(如键盘)向计算机内部(如内存)输入和从内存向外部输出设备(显示器)输出的过程。这种输入输出的过程被形象的比喻为“流”。
2.2、“流”的特性
有序连续、具有方向性
3、C++IO
C++系统实现了一个庞大的类库,其中ios为基类,其他都是直接或者间接派生自ios类
cerro和clog是标准错误输出流
在C++流类库中定义了四个全局流对象:cin、cout、cerro、clog
cin为标准输入流对象,键盘为其对应的标准设备
cout标准输出流对象,显示器为标准设备
注:
1、cin为缓冲流。键盘输入的数据保存在缓冲区中,当要提取时,是从缓冲区中拿。如果一次输入过多,会留在那儿慢慢用,如果输入错了,必须在回车之前修改,如果回车键按下就无法挽回了。只有把输入缓冲区中的数据取完后,才要求输入新的数据。不可能用刷新来清除缓冲区,所以不能输错,也不能多输
2、输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对应位置位(置1),程序继续。
3、空格和回车都可以作为数据之间的分格符,所以多个数据可以在一行输入,也可以分行输入。但如果是字符型和字符串,则空格(ASCII码为32)无法用cin输入,字符串中也不能有空格。回车符也无法读入。
4、文件流对象(读写序列化和反序列化)
操作步骤:
文件的操作步骤:
1、定义一个文件流对象
2、使用文件流对象打开一个磁盘文件
3、使用提取或插入运算符对文件进行读写操作
4、关闭文件
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class ServerInfo
{
public:
char m_ip[32];//ip
int m_port;//端口
};
class ConfigManger
{
public:
ConfigManger(const char* configfile = "bitserver.config")
:m_configfile(configfile)
{
}
void WriteBin(const ServerInfo& info)
{
ofstream ofs(m_configfile, ifstream::in | ifstream::binary);
ofs.write((const char*)& info, sizeof(ServerInfo));
ofs.close();
}
void ReadBin(ServerInfo& info)
{
ifstream ifs(m_configfile, ifstream::out | ifstream::binary);
ifs.read((char*)& info, sizeof(ServerInfo));
ifs.close();
}
void WriteText(const ServerInfo& info)
{
ofstream ofs(m_configfile);
ofs << info.m_ip << endl;
ofs << info.m_port << endl;
ofs.close();
}
void ReadText(ServerInfo& info)
{
ifstream ifs(m_configfile);
ifs >> info.m_ip;
ifs >> info.m_port;
ifs.close();
}
private:
string m_configfile;//配置文件
};
int main()
{
ConfigManger cfgMgr;
ServerInfo wtinfo;
ServerInfo rdinfo;
strcpy(wtinfo.m_ip, "127.0.0.1");
wtinfo.m_port = 80;
// 二进制读写
cfgMgr.WriteBin(wtinfo);
cfgMgr.ReadBin(rdinfo);
cout << rdinfo.m_ip << endl;
cout << rdinfo.m_port << endl;
// 文本读写
cfgMgr.WriteText(wtinfo);
cfgMgr.ReadText(rdinfo);
cout << rdinfo.m_ip << endl;
cout << rdinfo.m_port << endl;
system("pause");
return 0;
}