概念
程序運行時產生的數據都屬於臨時數據,程序一旦運行結束都會被釋放,通過文件可以將數據持久化
C++中對文件操作需要包含頭文件
文件類型分為兩種:
- 文本文件:文件以文本的ASCII碼形式存儲在計算機中
- 二進制文件:文件以文本的二進制形式存儲在計算機中,用户一般不能直接讀懂它們
操作文件的三大類:
- fstream : 讀寫操作
- ifstream: 讀操作
- ofstream:寫操作
寫文本文件
寫文件步驟如下:
- 包含頭文件
#include <fstream> - 創建流對象
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>
using namespace std;
#include<string>
#include<fstream>
void test()
{
ofstream ofs;
ofs.open("text.txt", ios::out);
ofs << "hello,world!" << endl;
ofs << "wow!" << endl;
ofs.close();
}
int main()
{
test();
}
總結:
- 文件操作必須包含頭文件fstream
- 讀文件可以利用 ofstream,或者fstream類
- 打開文件時候需要指定操作文件的路徑,以及打開方式·
- 利用<<可以向文件中寫數據
- 操作完畢,要關閉文件
讀文本文件
讀文件步驟如下:
- 包含頭文件
#include <fstream> - 創建流對象
ifstream ifs; - 打開文件並判斷文件是否打開成功
ifs.open("文件路徑",打開方式); - 讀數據
四種方式讀取 - 關閉文件
ifs.close();
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
void test()
{
ifstream ifs;
ifs.open("text.txt", ios::in);
if (!ifs.is_open())
{
//文件打開成功時,is_open()返回1,失敗時,返回0
cout << "文件打開失敗" << endl;
return;
}
//讀取方式一:
//char buf[1024] = { 0 };
//while (ifs >> buf) {
// cout << buf << endl;
//}
// 讀取方式二:
//char buf[1024] = { 0 };
//while (ifs.getline(buf,1024))
//{
// 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;
}
}
int main()
{
test();
}
總結:
- 讀文件可以利用 ifstream ,或者fstream類
- 利用is_open函數可以判斷文件是否打開成功
- 最後close關閉文件
寫二進制文件
以二進制的方式對文件進行讀寫,操作打開方式要指定為ios:binary
二進制方式寫文件主要利用流對象調用成員函數write
函數原型:ostream& write(const char *buffer,int len); 參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
class Person {
public:
char m_Name[64];
int m_Age;
};
void test()
{
ofstream ofs("test.txt", ios::binary | ios::out);
Person p = { "張三",18 };
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
int main()
{
test();
}
讀二進制文件
二進制方式讀文件主要利用流對象調用成員函數read
函數原型:istream& read (char *buffer,int len); 參數解釋:字符指針buffer指向內存中一段存儲空間。len是讀寫的字節數
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
class Person {
public:
char m_Name[64];
int m_Age;
};
void test()
{
ifstream ifs("test.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "file open failed" << endl;
return;
}
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << p.m_Name << endl;
cout << p.m_Age << endl;
ifs.close();
}
int main()
{
test();
}
文件輸入流對象可以通過read函數,以二進制方式讀數據.