小程序免費(fèi)制作網(wǎng)站2021年10月新聞?wù)?/h1>
1.文本文件 寫文件
#include "iostream"
#include "fstream"
using namespace std;
/** 文件操作** 程序運(yùn)行時(shí)產(chǎn)生的數(shù)據(jù)都屬于臨時(shí)數(shù)據(jù),程序一旦結(jié)束都會(huì)被釋放* 通過文件可以將數(shù)據(jù)持久化* C++中對(duì)文件操作需要包含頭文件<fstream>** 文件類型分為兩種:* 文本文件:文件以文本的ASCII碼形式存儲(chǔ)在計(jì)算機(jī)中* 二進(jìn)制文件:文件以文本的二進(jìn)制形式存儲(chǔ)在計(jì)算機(jī)中,用戶一般不能直接讀懂他們** 操作文件的三大類:* 1.ofstream:寫操作* 2.ifstream:讀操作* 3.fstream:讀寫操作** 寫文件:* 1.包含頭文件 #include<fstream>* 2.創(chuàng)建流對(duì)象 ofstream ofs;* 3.打開文件 ofs.open("文件路徑",打開方式);* 4.寫數(shù)據(jù) ofs<<"寫入的數(shù)據(jù)";* 5.關(guān)閉文件 ofs.close();** 文件打開方式:* ios::in 為讀文件而打開文件* ios::out 為寫文件而打開文件* ios::ate 初始位置:文件尾* ios::app 追加方式寫文件* ios::trunc 如果文件存在先刪除,再創(chuàng)建* ios::binary 二進(jìn)制方式* 注意:文件打開方式可以配合使用,利用|操作符* 例如:用二進(jìn)制方式寫文件 ios:binary|ios:out**///文本文件 寫文件
void test01(){//1.包含頭文件//2.創(chuàng)建流對(duì)象ofstream ofs;//3.指定打開的方式ofs.open("test.txt",ios::out);//4.王文件中寫內(nèi)容ofs<<"姓名:張三"<<endl;ofs<<"性別:男"<<endl;ofs<<"年齡:18"<<endl;//5.關(guān)閉文件ofs.close();
}int main() {test01();return 0;
}
2.文本文件 寫文件
#include "iostream"
#include "fstream"using namespace std;/** 讀文件** 讀文件和寫文件步驟相似*/
void test01() {ifstream ifs;ifs.open("test.txt", ios::in);bool boolTemp = ifs.is_open();if (!boolTemp) {cout << "文件打開失敗" << endl;return;}//4.讀數(shù)據(jù)//第一種
// char buf[1024]={0};
// while(ifs>>buf){
// cout<<buf<<endl;
// }// //第二種
// string buf;
// while(getline(ifs,buf)){
// cout<<buf<<endl;
// }//第三種char c;while ((c = ifs.get()) != EOF) { //EOF 文件結(jié)果尾部的標(biāo)志cout << c;}//5.關(guān)閉文件ifs.close();
}int main() {test01();return 0;
}
3.二進(jìn)制文件 讀寫
#include "iostream"using namespace std;#include "fstream"/** 二進(jìn)制讀寫文件** 二進(jìn)制方式文件主要利用流對(duì)象調(diào)用成員函數(shù) write* 函數(shù)原型 ostream & write(const char * buffer,int len)*/class Person {
public:char m_Name[64]; //姓名int m_Age; //年齡
};void test01() {//1.頭文件//2.創(chuàng)建流對(duì)象ofstream ofs;//3.打開文件ofs.open("person.txt", ios::out | ios::binary);//4.寫文件Person p = {"張三", 19};ofs.write((const char *) &p, sizeof(p));//5.關(guān)閉文件ofs.close();
}//讀文件
void test02() {//1.頭文件//2.創(chuàng)建流對(duì)象ifstream ifs;//3.打開文件ifs.open("person.txt", ios::in | ios::binary);//4.寫文件if (!ifs.is_open()) {cout << "文件打開失敗" << endl;return;}Person p;ifs.read((char *) &p, sizeof(p));cout << "姓名:" << p.m_Name << ";年齡:" << p.m_Age << endl;//5.關(guān)閉文件ifs.close();
};int main() {test01();test02();return 0;
}