C++读写文件要点总结
1、使用C++读写文件常用的操作:
1)导入头文件fstream和string ;
2)创建文件流file,输入使用ifstream类型,输出使用ofstream类型;
3)调用file.open(),打开文件;
4)使用getLine(),逐行读取输入文件中的字符;
5)使用“<<”操作符将字符串写入到文件流中;
6)调用file.close(),关闭文件。
2、函数解释
1)file.open()
void open(const char* _Filename, ios_base::openmode _Mode = ios_base::out, int _Prot = ios_base::_Default_open_prot) ;
// _Prot is an extension
常用的打开模式:
ios::in 从文件中读取;
ios::out 写入到文件,且会覆盖掉文件中的原内容;
ios::app 以在文件末尾添加的方式写入文件。
2)getLine()
void getLine(std::istream &_Istr ,std::string &Str) ;
将Istr输入流中的一行字符读取到Str中,连续调用会逐行读取。