天天看點

C++學習筆記day--18檔案操作

1、文本檔案–寫檔案

#include<iostream>
#include<fstream>
using namespace std;

//文本檔案 寫檔案

void test01()
{
	//1、包含頭檔案 fstream

	//2、建立流對象
	
	ofstream ofs;

	//3、指定打開方式
	ofs.open("test.txt", ios::out);

	//4、寫内容
	ofs << "姓名:張三" << endl;
	ofs << "性别:男  " << endl;
	ofs << "年齡:18  " << endl;

	//5、關閉檔案
	ofs.close();

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

2、文本檔案–讀檔案

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

//文本檔案 讀檔案

void test01()
{
	//1、包含頭檔案 fstream

	//2、建立流對象

	ifstream ifs;

	//3、指定打開方式
	ifs.open("test.txt", ios::in);

	if (!ifs.is_open())
	{
		cout << "檔案打開失敗" << endl;
		return;
	 }

	//4、讀資料

	//第一種
	//char buf[1024] = { 0 };
	/*while (ifs >> buf)
	{
		cout << buf << endl;
	}*/

	//第二種
	/*while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}*/

	//第三種
	/*string buf;
	while( getline(ifs,buf))
	{
		cout << buf << endl;
	}
*/
	//第四種
	char c;
	while ((c = ifs.get()) != EOF)//EOF END of FILE
	{
		cout << c;
	}
	//5、關閉檔案
	ifs.close();

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

3、二進制檔案–寫檔案

#include<iostream>
#include<fstream>
using namespace std;

//二進制檔案 寫檔案
class Person
{
public:
	char m_Name[64];
	int m_Age;

};

void test01()
{
	//1、包含頭檔案 fstream

	//2、建立流對象

	ofstream ofs;

	//3、指定打開方式
	ofs.open("person.txt", ios::out|ios::binary);

	//4、寫内容
	Person p = { "張三",18 };
	ofs.write((const char *)&p, sizeof(Person));
	

	//5、關閉檔案
	ofs.close();

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

4、二進制檔案–讀檔案

#include<iostream>
#include<fstream>
using namespace std;

//二進制檔案 寫檔案
class Person
{
public:
	char m_Name[64];
	int m_Age;

};

void test01()
{
	//1、包含頭檔案 fstream

	//2、建立流對象

	ifstream ifs;

	//3、指定打開方式,判斷檔案是否打開成功
	ifs.open("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "檔案打開失敗" << endl;
		return;
	}

	//4、讀檔案
	Person p;
	ifs.read(( char *)&p, sizeof(Person));

	cout << "姓名:" << p.m_Name << endl;
	cout << "年齡:" << p.m_Age << endl;


	//5、關閉檔案
	ifs.close();

}
int main()
{
	test01();
	system("pause");
	return 0;
}
           
c++

繼續閱讀