C++ 文件操作以及二进制操作进行对序列化

这里主要是讨论fstream的内容:

#include <fstream> //文件操作需要引拥的头文件
ofstream         //文件写操作 内存写入存储设备 
ifstream         //文件读操作,存储设备读区到内存中
fstream          //读写操作,对打开的文件可进行读写操作 

1.打开文件(ifstream)

在fstream类中,成员函数open()实现打开文件的操作,从而将数据流和文件进行关联,通过ofstream,ifstream,fstream对象进行对文件的读写操作

函数:open()

public member function
 
void open ( const char * filename,
            ios_base::openmode mode = ios_base::in | ios_base::out );
 
void open(const wchar_t *_Filename,
        ios_base::openmode mode= ios_base::in | ios_base::out,
        int prot = ios_base::_Openprot);
 
参数: filename   操作文件名
            mode        打开文件的方

            prot         打开文件的属性                            //基本很少用到,在查看资料时,发现有两种方式
————————————————

打开文件的方式在ios类(所以流式I/O的基类)中定义,有如下几种方式:

ios::in    为输入(读)而打开文件
ios::out    为输出(写)而打开文件
ios::ate    初始位置:文件尾
ios::app    所有输出附加在文件末尾
ios::trunc    如果文件已存在则先删除该文件
ios::binary    二进制方式

这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如

ofstream out;
out.open("Hello.txt", ios::in|ios::out|ios::binary)                 //根据自己需要进行适当的选取

 2.下面是对文件的读写操作,注意读写完成后记得close操作

#include  <iostream>
#include  <fstream>
#include  <string>
using namespace std;
/*********************************************
 * 
 * test function:将文件写入到另外一个文件中去
 * 
 * ******************************************/
void  test()
{
   char* filename="/home/zjl/source.txt";
   char* filename1="/home/zjl/target.txt";
   ifstream ism(filename,ios::in); //读取文件
   ofstream osm(filename1,ios::out|ios::app);//写入到target 文件中
   if(!ism){
		cout<<"open fail"<<endl;
		return ;
	}
	//read file
	char ch;
	while(ism.get(ch)){
		cout<<ch;
		cout<<"read  success";
		//写入到文件中
		osm.put(ch);
	}
	ism.close();
	osm.close();
	//将读取的问件再写入到target 文件中

}
/*文本文件读写*/
int main()
{   test();
	return 0;
}

3.二进制文件序列化操作

void  test2()
{
#if 1
	/**写将对象写进去*/
	Person p1(10,20);
	Person p2(30,40); //在内存中是以二进制存储的
	//把p1,p2写到文件里面去
	char* TargetName="/home/zjl/target.txt";
	ofstream  osm(TargetName,ios::out|ios::binary);
	osm.write((char*)&p1,sizeof(Person)); //将对象以二进制写入到文件
	osm.write((char*)&p2,sizeof(Person));//将对象P2以二进制写入到文件中去
    //写完之后记得关闭文件
	osm.close();	
#endif
   /*对文件进行读操作*/
   ifstream ism(TargetName,ios::in|ios::binary);
   /*将前面写的的数据拿出来进行读取操作*/
   Person  p3,p4;
   ism.read((char*)&p3,sizeof(Person)); //从文件中读取数据
   ism.read((char*)&p4,sizeof(Person));//从文件中读取P2对象数据

   p3.Show();
   p4.Show();

}
发布了102 篇原创文章 · 获赞 26 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42145502/article/details/103756747
今日推荐