C++讀寫文件操作


一、讀寫文本文件

1.1 寫文件

寫文件步驟如下:

  1. 包含頭文件

    #include <fstream>

  2. 創建流對象

    ofstream ofs;

  3. 打開文件

    ofs.open("文件路徑",打開方式);

  4. 寫數據

    ofs << "寫入的數據";

  5. 關閉文件

    ofs.close();

文件打開方式:

打開方式 解釋
ios::in 為讀文件而打開文件
ios::out 為寫文件而打開文件
ios::ate 初始位置:文件尾
ios::app 追加方式寫文件
ios::trunc 如果文件存在先刪除,再創建
ios::binary 二進制方式

注意: 文件打開方式可以配合使用,利用|操作符

例如:用二進制方式寫文件 ios::binary | ios:: out

示例:

#include <fstream>

void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);

	ofs << "姓名:張三" << endl;
	ofs << "性別:男" << endl;
	ofs << "年齡:18" << endl;

	ofs.close();
}

int main() {

	test01();

	system("pause");

	return 0;
}

總結:

  • 文件操作必須包含頭文件 fstream
  • 讀文件可以利用 ofstream ,或者fstream類
  • 打開文件時候需要指定操作文件的路徑,以及打開方式
  • 利用 <<可以向文件中寫數據
  • 操作完畢,要關閉文件

1.2讀文件

讀文件與寫文件步驟相似,但是讀取方式相對於比較多

讀文件步驟如下:

  1. 包含頭文件

    #include <fstream>

  2. 創建流對象

    ifstream ifs;

  3. 打開文件並判斷文件是否打開成功

    ifs.open("文件路徑",打開方式);

  4. 讀數據

    四種方式讀取

  5. 關閉文件

    ifs.close();

示例:

#include <fstream>
#include <string>
void test01()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);

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

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

	//第二種
	//char buf[1024] = { 0 };
	//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)
	{
		cout << c;
	}

	ifs.close();


}

int main() {

	test01();

	system("pause");

	return 0;
}

總結:

  • 讀文件可以利用 ifstream ,或者fstream類
  • 利用is_open函數可以判斷文件是否打開成功
  • close 關閉文件

二、讀寫二進制文件

以二進制的方式對文件進行讀寫操作

打開方式要指定為 ios::binary

2.1 寫文件

二進制方式寫文件主要利用流對象調用成員函數write

函數原型 :ostream& write(const char * buffer,int len);

參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數

示例:

#include <fstream>
#include <string>

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

//二進制文件  寫文件
void test01()
{
	//1、包含頭文件

	//2、創建輸出流對象
	ofstream ofs("person.txt", ios::out | ios::binary);
	
	//3、打開文件
	//ofs.open("person.txt", ios::out | ios::binary);

	Person p = {"張三"  , 18};

	//4、寫文件
	ofs.write((const char *)&p, sizeof(p));

	//5、關閉文件
	ofs.close();
}

int main() {

	test01();

	system("pause");

	return 0;
}

總結:

  • 文件輸出流對象 可以通過write函數,以二進制方式寫數據

2.2 讀文件

二進制方式讀文件主要利用流對象調用成員函數read

函數原型:istream& read(char *buffer,int len);

參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數

示例:

#include <fstream>
#include <string>

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

void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打開失敗" << endl;
	}

	Person p;
	ifs.read((char *)&p, sizeof(p));

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

int main() {

	test01();

	system("pause");

	return 0;
}
  • 文件輸入流對象 可以通過read函數,以二進制方式讀數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM