[编程笔记] C++文件操作

/*
	C++文件操作
*/
#include <fstream>
#include <iostream>
using namespace std;

class A {
	public:
		int data;
		char str[20];
};

int main(void)
{	
	//1. write into the file
	A a;
	a.data = 200;
	strcpy(a.str, "come on");

	fstream file("d://data.txt", ios::out|ios::binary);
	if(file.fail())	{
		cout << "Can not open the file" << endl;
		return 0;
	}
	file.write( (char*)(&a), sizeof(a) );
	file.close();


	//2. read file's data
	file.open("d://data.txt", ios::in|ios::binary);
	if(file.fail())	{
		cout << "Can not open the file" << endl;
		return 0;
	}	
	A b;
	file.read( (char*)(&b), sizeof(b) );	
	cout << b.data << endl;
	cout << b.str<< endl;
	file.close();
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cp_oldy/article/details/88299598