首先我们先写一下文件,文件写入需要分为五个步骤,一定要谨记哦!
第一步:包含头文件fstream
#include<fstream>//头文件包含
第二步:创建流对象
ofstream ofs;
第三步:指定打开方式
ofs.open("test.txt", ios::out);
第四步:写内容
ofs << "姓名:张三" << endl;
ofs << "性别: 男" << endl;
ofs << "年龄: 18" << endl;
第五步:关闭文件
ofs.close();
完整代码及运行结果如下:
#include<iostream>
using namespace std;
#include<fstream>//头文件包含
void test01() {
//1.包含头文件fstream
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "性别: 男" << endl;
ofs << "年龄: 18" << endl;
//5.关闭文件
ofs.close();
}
int main() {
test01();
system("pause");
return 0;
}
结果:
接下来是读文件。读文件有四种方法:
读文件步骤也是五步:
第一步:包含头文件
#include<fstream>
第二步:创建流对象
ifstream ifs;
第三步:打开文件并判断文件是否打开成功
ifs.open("文件路径",打开方式);
第四步:读数据
读数据我们会写四种不同的方式。
第一种:
//第一种:
char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}
第二种:
//第二种:
char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
}
第三种:
//第三种:
string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
}
第四种:
//第四种:
char c;
//一个字符一个字符的读取,效率低,不建议用
while ((c = ifs.get()) != EOF) {
cout << c;
}
第五步:关闭文件
ifs.close();
完整代码如下:
#include<iostream>
using namespace std;
#include<fstream> //包含头文件
#include<string>
void test02() {
//1. 包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件并判断是否打开成功
ifs.open("test.txt",ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//4.读数据
//第一种:
/*char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}*/
//第二种:
/*char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf))) {
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;
}
//5.关闭文件
ifs.close();
}
int main() {
test02();
system("pause");
return 0;
}
结果: