文件操作:
c++中對文件操作需要包含頭文件 < fstream?>
文本文件:以ASCII碼形式儲存
二進(jìn)制文件:以二進(jìn)制文件儲存(讀不懂)
操作文件三大類:
讀:ifstream ; 寫:ofstream ; 讀寫:fstream
一.文本文件:
1.寫文件:
步驟:
(1)包含頭文件:#include <fstream>
(2)創(chuàng)建流對象:ofstream ofs;
(3)打開文件:ofs.open(“文件路徑”,打開方式);
(4)寫數(shù)據(jù):ofs <<? “數(shù)據(jù)”;
(5)關(guān)閉文件:ofs.close();
文件打開方式:
注:1.可用 | 操作符運(yùn)用多種打開方式。
2.可在創(chuàng)建流對象的時(shí)候直接打開文件并指定打開方式:
ofstream ofs("test.txt", ios::out | ios::binary);
例:文章來源:http://www.zghlxwxcb.cn/news/detail-820007.html
void test01()
{
ofstream ofs;
ofs.open("test.txt", ios::out);//不寫路徑,默認(rèn)創(chuàng)建在與代碼項(xiàng)目同文件夾
ofs << "hello world" << endl;
ofs << "hello world" << endl;
ofs.close();
}
2.讀文件:
步驟:
(1)包含頭文件:#include <fstream>
(2)創(chuàng)建流對象:ifstream ifs;
(3)打開文件,并判斷是否打開成功:
ifs.open(“文件路徑”,打開方式);
ifs下有一 is_open 函數(shù),返回bool類型值。
if (!ifs.is_open())//這里取反
{
cout << "文件打開失敗" << endl;
return;
}
(4)讀數(shù)據(jù):四種方式。
(5)關(guān)閉文件:ifs.close();
讀文件的四種方式:
a.第一種:char[ ] + ifs >>?
char buf[1024] = { 0 };
while (ifs >> buf)//按空格和回車循環(huán)
{
cout << buf << endl;
}
b.第二種:char[ ] + ifs.getline()
char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf)))//按行循環(huán)
{
cout << buf << endl;
}
c.第三種:string + getline()
string buf;
while (getline(ifs, buf))
{
cout << buf << endl;
}
d.第四種:char + ifs.get()? (不推薦)
char c;
while ((c = ifs.get()) != EOF)
{
cout << c;
}
二.二進(jìn)制文件:
指定打開方式為:ios::binary
1.寫文件:
調(diào)用流對象的成員函數(shù) write(const char*,寫入最大字符數(shù))
例:
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test03()
{
ofstream ofs("test.txt", ios::out | ios::binary);
Person p = { "張三",18 };
ofs.write((const char*)(&p), sizeof(Person));
ofs.close();
}
2.讀文件:
調(diào)用流對象的成員函數(shù) read(char*,讀出最大字符數(shù))文章來源地址http://www.zghlxwxcb.cn/news/detail-820007.html
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test04()
{
Person p;
ifstream ifs;
ifs.open("test.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打開失敗" << endl;
return;
}
ifs.read((char*) & p, sizeof(Person));
cout << p.m_Name << " " << p.m_Age << endl;
}
到了這里,關(guān)于c++學(xué)習(xí)第十一講---文件操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!