C++ 将自定义数据存储到文件

 将自定义数据存储到文件并读取的代码片段:

struct Stuent
{
	Stuent(){}

	Stuent(std::string n, int a, int s)
		:name(n), age(a), score(s)
	{
	}

	std::string name;
	int age = 0;
	int score = 0;

	void log(){
		std::cout << "name:" << name.c_str() << std::endl;
		std::cout << "age:" << age << std::endl;
		std::cout << "score:" << score << std::endl;
	}
};

int main()
{
	{
		std::ofstream fin("a.dat", std::ios::binary);
		Stuent aa("xiaoming", 26, 100);
		std::string str = "blank space";
		fin.write((const char *)&aa, sizeof(Stuent));
		//将student中的内容 写入到文件
		fin.write((const char *)&str, sizeof(std::string));
		fin.close();
	}

	{
		Stuent *stu=new Stuent;
		std::string str;
		std::fstream fin("a.dat", std::ios::binary | ios::in);
		fin.read((char *)stu, sizeof(Stuent));
		//fin.seekg(sizeof(Stuent), ios::beg);
		fin.read((char *)&str, sizeof(std::string));
		fin.close();

		std::cout << str.c_str() << std::endl;
		stu->log();
		delete stu;
	}
	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/auccy/article/details/81490474