操作文件的三大类
- ifstream 读操作
- ofstream 写操作
- fstream 读写操作
基本步骤
与我在JAVA中讲的步骤基本一致
包含头文件
#include<fstream>
选择流
ofsteam ofs;
打开文件
ofs.opean("文件路径",""打开方式)
操作
ofs<<"写入数据"
关闭流
ofs.close()
写入
#include<iostream>
#include<fstream>
using namespace std;
int main() {
//选择流
ofstream ofs;
//打开文件
ofs.open("test.txt", ios::out);
//操作
ofs << "你好,C++" << endl;
ofs << "这是我认识你的第18天" << endl;
ofs << "一起努力吧!" << endl;
//关闭流
ofs.close();
}
读取
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
//选择流
ifstream ifs;
//选择源
ifs.open("C:/unintall.log", ios::in);
//操作
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return 0;
}
//按行读取
/*char buffer[1024] = { NULL };
while (ifs.getline(buffer, sizeof(buffer))) {
cout << buffer << endl;
}*/
//以字符串读取
string buf = { NULL };
while ( getline(ifs,buf)) {
cout << buf << endl;
}
//关闭流
ifs.close();
}
操作符
流成员函数
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main() {
int num = 18;
double test = 1556216.31616;
cout << "流成员函数" << endl;
cout.width(15);
cout.fill('*');
cout.setf(ios::left);
//1.宽15 空白‘*’
cout << num << endl;
cout.fill();
//2.10 8 16 进制
cout.setf(ios::dec);
cout << num << endl;
cout.unsetf(ios::dec);
cout.setf(ios::oct);
cout << num << endl;
cout.unsetf(ios::oct);
cout.setf(ios::hex);
cout << num << endl;
cout.unsetf(ios::hex);
//3.精度
cout.precision(4);
cout.setf(ios::scientific);
cout << test << endl;
cout.unsetf(ios::scientific);
cout.setf(ios::fixed);
cout << test << endl;
cout.unsetf(ios::fixed);
cout << "控制符" << endl;
//1.
cout <<setiosflags(ios::left) << setw(15) << setfill('*') << num << endl;//1
//2
cout << dec << num << endl;
cout << oct << num << endl;
cout << hex << num << endl;
//3
cout << setprecision(4) << setiosflags(ios::scientific) << test << endl;
cout << test <<endl;
cout << setprecision(4) << setiosflags(ios::fixed) << test << endl;
}