C++學習筆記----讀寫檔案

万舜發表於2024-06-24

讀寫檔案

class Perso
{
	public:
		char m_Name[64];
		int m_Age;
};

/*
ios::in   read file;
ios::out   write file; 
ios::ate	檔案尾部
ios::app	追加寫入檔案
ios::trunc	如果檔案已存在則刪除後建立
ios::binary  二進位制方式

ios::binary | ios ::out  二進位制寫

標頭檔案:
ifstream 讀
ofstream 寫
fstream  讀寫
<< 左移運算子輸出資料	到檔案
>> 右移運算子讀入資料	到記憶體
記得關閉資料close();
*/
void test()
{

	//寫入
	//ofstream ofs;
	//ofs.open("D:\\Project\\CPP\\demo\\demo1\\a.txt", ios::out);
	//ofs.open("b.txt", ios::out);
	//ofs <<"aaaaaaaaaaaaaaaa"<<endl
		//<<"bbbbbbbbbbbbbbbbb"<<endl;
	//ofs.close();
}

void test02()
{
	//讀取
	ifstream ifs;

	ifs.open("b.txt", ios::in);
	//判斷檔案是否開啟成功
	if(!ifs.is_open())
	{
		cout<<"open fail"<<endl;
		
	}
	
	/*
	char buff[1024] = {0};
	while (ifs >> buff)
	{
		cout<<buff<<endl;
	}
	//一行一行塊讀
	while(ifs.getline(buff, sizeof(buff)))
	{
		cout<<buff;
	}
	*/
	/*
	字串一行一行讀
	string buff;
	while(getline(ifs,buff))
	{
		cout<<buff;
	}
	*/
	//字元一個一個讀
	char c;
	while((c = ifs.get()) != EOF) //EOF end of file
	{
		cout<<c;
	}
	ifs.close();
}

void test03()
{
	ofstream ofs("person.txt", ios::out | ios::binary);
	Perso p = {"zhangsan", 18};
	ofs.write((const char*)&p, sizeof(Person));
	ofs.close();
}
void test04()
{
	ifstream ifs;
	ifs.open("person.txt", ios::in | ios::binary);
	if(!ifs.is_open())
	{
		cout<<"open fail"<<endl;
	}
	Perso p;
	ifs.read((char*)&p, sizeof(Perso));
	cout<<p.m_Name<<p.m_Age<<endl;
	ifs.close();
}



int main()
{
	test04();
	
	
	
	system("pause");
	system("cls");
	return 0;
}

相關文章