C++ 练习day8

文件输入输出

#include<iostream>
using namespace std;
#include<iomanip>
#include<fstream>
#include<vector>
#include<string>
class Person {
private:
	char name[20];
	char id[18];
	int age;
	char addr[20];
public:
	Person() {};
	Person(char *n, char* pid, int Age, char* Addr) {
		strcpy_s(name, n);//name[]退化为指针
		strcpy_s(id, pid);
		age = Age;
		strcpy_s(addr, Addr);

	}
	void display() {
		cout << name << "\t" << id << "\t" << age << "\t" << addr << endl;
	}
};
int main(int argc, const char* argv[])
{
	vector<Person>v;
	char ch;
	ofstream out("d:/person.dat", ios::out | ios::app | ios::binary);
	char Name[20], ID[18], Addr[20];
	int Age;
	cout << "------输入个人档案------" << endl << endl;
	do {
		cout << "姓名: ";
		cin >> Name;
		cout << "身份证号: ";
		cin >> ID;
		cout << "年龄: ";
		cin >> Age;
		cout << "地址: ";
		cin >> Addr;
		Person per(Name, ID, Age, Addr);
		out.write((char*)&per, sizeof(per));
		cout << "enter another person" << endl;
		cin >> ch;
	} while (ch == 'y');
	out.close();
	ifstream in("d:/person.dat", ios::in | ios::binary);
	Person s;
	in.read((char*)&s, sizeof(s));
	//eof()函数可以帮助我们用来判断文件是否为空,抑或是判断其是否读到文件结尾。
	while (!in.eof())
	{
		v.push_back(s);
		in.read((char*)&s, sizeof(s));
	}
	cout << "\n---------从文件中读出的数据--------" << endl << endl;//L15
	auto pos = v.begin();
	for (pos = v.begin(); pos != v.end(); pos++)
		(*pos).display();

	system("pause");
	return 0;
}
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
class Employee{
private:
    int number ,age;
    char name[20];
    double sal;
public:
    Employee(){}
    Employee(int num,char* Name,int Age, double Salary){
        number=num;
        strcpy(name,Name);
        age=Age;
        sal=Salary;
    }
    void display(){
        cout<<number<<"\t"<<name<<"\t"<<age<<"\t"<<sal<<endl;
    }
};

int main(){
    ofstream out("D:/Employee.dat",ios::out);	//定义随机输出文件
    Employee e1(1,"张三",23,2320);
    Employee e2(2,"李四",32,3210);
    Employee e3(3,"王五",34,2220);
    Employee e4(4,"刘六",27,1220);
    out.write((char*)&e1,sizeof(e1));		//按e1,e2,e3,e4顺序写入文件
    out.write((char*)&e2,sizeof(e2));
    out.write((char*)&e3,sizeof(e3));
    out.write((char*)&e4,sizeof(e4));

     //下面的代码将e3(即王五)的年龄改为40岁   
    Employee e5(3,"王五",40,2220);
    out.seekp(3*sizeof(e1));		//指针定位到第3(起始为0)个数据块
    out.write((char*)&e5,sizeof(e5));	//将e5写到第3个数据块位置,覆盖e3
    out.close();			//关闭文件
    system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

师父祭天法力无边

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值