第二十一章流 13seekp()和seekg()函数的结合使用

//第二十一章流 13seekp()和seekg()函数的结合使用

/*#include <iostream>

#include <fstream>

#include <iomanip>

using namespace std;

const int num = 10;

struct people

{

	char name[num];

	int age;

	float pay;

};







const char*file = "people13.txt";

void deleteline(){ while(cin.get() !='\n') continue; }



int main()

{

	//people pp={"陈涛",25,945.34f};	

	//ofstream fout(file,ios::out|ios::binary);

	//fout.write((char*)&pp, sizeof pp);

	//fout.close();

	//people pp1={"李力持",45,1065.58f};

	//fout.open(file,ios::in|ios::out|ios::binary);

	//fout.seekp(sizeof pp, ios::beg);

	//fout.write((char*)&pp1,sizeof pp1);

	//fout.close();



	people pp={0};

	ofstream fout(file,ios::out|ios::binary);

	bool quit = true;

	while(quit)

	{

	    cout<<"输入名称:";

		cin.get(pp.name,num);

		cin.ignore();

		cout<<"输入年龄";

		cin>>pp.age;

		cout<<"输入薪水";

		cin>>pp.pay;

		fout.write((char*)&pp, sizeof pp);

		cout<<"是否继承输入,是按y,否按n:"<<endl;

		char choice;

		cin>>choice;

		if(choice=='y'){

		    deleteline();

			continue;

		}else

			quit = false;	

	}

	fout.close();

	cout<<fixed;









	fstream InOut;

	InOut.open(file,ios::in|ios::out|ios::binary);

	int count=0;

	if(InOut.is_open())

	{

		InOut.seekp(0);//设置函数将指针定位到文件头

		cout<<"当前内容为:"<<file<<endl;

		while(InOut.read((char*)&pp, sizeof pp))

		{

			cout<<count++<<":"<<setw(num)<<pp.name<<":"<<setprecision(0)<<setw(12)<<pp.age<<setprecision(2)<<setw(16)<<pp.pay<<endl;

		}

		if(InOut.eof())//当函数遇到EOF后

		{

			InOut.clear();

		}else{

		    cout<<"读取错误"<<file<<endl;

			exit(EXIT_FAILURE);

		}

	}else{

	    cout<<file<<"不能找开\n";

		exit(EXIT_FAILURE);

	}



	cout<<"输入你希望改变的编号:"<<endl;

	long line;

	cin>>line;

	deleteline();

	if(line<0 || line>=count)

	{

	    cout<<"无效编号"<<endl;

		exit(EXIT_FAILURE);

	}

	streampos place = line*sizeof pp;

	InOut.seekg(place);

	if(InOut.fail()){

	   cout<<"尝试查询失败"<<endl;

	   exit(EXIT_FAILURE);

	}

	InOut.read((char*)&pp, sizeof pp);

	cout<<"你的选择为:";

	cout<<line<<":"<<setw(num)<<pp.name<<":"<<setprecision(0)<<setw(12)<<pp.age<<setprecision(2)<<setw(16)<<pp.pay<<endl;

	if(InOut.eof())

	{

		InOut.clear();

	}



	cout<<"输入名字:"<<endl;

	cin.get(pp.name,num);

	deleteline();



	cout<<"输入年龄:"<<endl;

	cin>>pp.age;

	cout<<"输入薪水"<<endl;

	cin>>pp.pay;



	InOut.seekp(place);

	InOut.write((char*)&pp,sizeof pp)<<flush;

	if(InOut.fail()){

		cout<<"尝试写入失败"<<endl;

		exit(EXIT_FAILURE);

	}



	count=0;

	InOut.seekg(0);

	cout<<"当前内容为:"<<file<<endl;

	while(InOut.read((char*)&pp, sizeof pp))

	{

			cout<<count++<<":"<<setw(num)<<pp.name<<":"<<setprecision(0)<<setw(12)<<pp.age<<setprecision(2)<<setw(16)<<pp.pay<<endl;

	}

	InOut.close();		

	cout<<"完成!";

    return 0;

}*/

  

你可能感兴趣的:(函数)