1.通过文件输出流对象,写入若干行文字;
2.关闭文件输出流对象,然后观察磁盘文件内容;
3.改用open函数创建文件输出流,并选择适当的文件操作方式;
4.在原内容的后面追加若干行新内容;
基本要求:能熟练运用文件各种操作编写程序测试并提交程序。
#include<iostream>
#include<fstream>//文件操作头文件
#include<string>
using namespace std;
void test01()
{
//2.创建流对象
ofstream ofs;
//3.打开文件
ofs.open("test.txt", ios::out);
//4.写数据
ofs << "姓名:路明非" << endl;
ofs << "年龄:18" << endl;
ofs << "性别:未知" << endl;
ofs << "籍贯:龙族" << endl;
//5.关闭文件
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
text文件写入 姓名 年龄 性别 籍贯信息:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream ofs;
ofs.open("test.txt", ios::out | ios::app);
ofs << "学校:XXX" << endl;
ofs << "婚配:XXX" << endl;
ofs.close();
system("pause");
return 0;
}
结果:在后面添加 学校 婚配 信息:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open())//判断是否打开
{
cout << "打开失败" << endl;
return 0;
}
string buf;//读文件
while (getline(ifs, buf))
{
cout << buf << endl;
}
ifs.close();
system("pause");
return 0;
}
运行查看结果: