文件操作
程序運行時產生的數據都屬於臨時數據,程序一旦運行結束都會被釋放。
通過文件可以將數據持久化
C++中對文件操作需要包含頭文件 < fstream >
文件類型分爲兩種:
- 文本文件 - 文件以文本的ASCII碼形式存儲在計算機中
- 二進制文件 - 文件以文本的二進制形式存儲在計算機中,用戶一般不能直接讀懂它們
操作文件的三大類:
3. ofstream:寫操作
4. ifstream: 讀操作
5. fstream : 讀寫操作
1 文本文件
1.1 寫文件
寫文件步驟如下:
- 包含頭文件
#include - 創建流對象
ofstream ofs; - 打開文件
ofs.open(“文件路徑”,打開方式); - 寫數據
ofs << “寫入的數據”; - 關閉文件
ofs.close();
文件打開方式:
打開方式 | 解釋 |
---|---|
ios::in | 爲讀文件而打開文件 |
ios::out | 爲寫文件而打開文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式寫文件 |
ios::trunc | 如果文件存在先刪除,再創建 |
ios::binary | 二進制方式 |
注意: 文件打開方式可以配合使用,利用 | 操作符
例如:用二進制方式寫文件 ios::binary | ios:: out
#include <iostream>
#include <fstream>
using namespace std;
void testfile1()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:張三" << endl;
ofs << "性別:男" << endl;
ofs << "年齡:18" << endl;
ofs.close();
}
int main()
{
testfile1();
system("pause");
return 0;
}
總結
文件操作必須包含頭文件 fstream
讀文件可以利用 ofstream ,或者fstream類
打開文件時候需要指定操作文件的路徑,以及打開方式
利用<<可以向文件中寫數據
操作完畢,要關閉文件
1.2 讀文件
讀文件與寫文件步驟相似,但是讀取方式相對於比較多
讀文件步驟如下:
- 包含頭文件
#include - 創建流對象
ifstream ifs; - 打開文件並判斷文件是否打開成功
ifs.open(“文件路徑”,打開方式); - 讀數據
四種方式讀取 - 關閉文件
ifs.close()
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void test11()
{
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)//一個一個讀取,==EOF說明接收完了
{
cout << c;
}
ifs.close();
}
int main()
{
test11();
system("pause");
return 0;
}
運行結果
總結
讀文件可以利用 ifstream ,或者fstream類
利用is_open函數可以判斷文件是否打開成功
close 關閉文件
2 二進制文件
以二進制的方式對文件進行讀寫操作
打開方式要指定爲 ios::binary
2.1 二進制寫文件
二進制方式寫文件主要利用流對象調用成員函數write
函數原型 :ostream& write(const char * buffer,int len);
參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Person
{
public :
char m_Name[64];
int m_Age;
};
void test22()
{
//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()
{
test22();
system("pause");
return 0;
}
運行結果(二進制)
總結
文件輸出流對象 可以通過write函數,以二進制方式寫數據
2.2 二進制讀文件
二進制方式讀文件主要利用流對象調用成員函數read
函數原型:istream& read(char *buffer,int len);
參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Person
{
public :
char m_Name[64];
int m_Age;
};
void test33()
{
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()
{
test33();
system("pause");
return 0;
}
運行結果
總結
文件輸入流對象 可以通過read函數,以二進制方式讀數據