文本文件输入
1.必须包含头文件fstream
2.需要声明一个或多个ofstream的对象,并以自己喜欢的方式对其进命名。
3.使用open()方法将ofstream的对象和文件关联起来,使用完文件后使用close方法将其关闭。
4.可以直接用ofstream类的构造函数 ofstream fout("a.txt")
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout;//可以直接用ofstream fout("a.txt")
char name[50];
cin>>name;
fout.open("a.txt");
fout<<name;
fout.close();
return 0;
}
iostream提供了一个预先定义好的名为cout的ostream的对象,所以cout有的方法 fout都可以用,比如cout<<name.
文本文件输出
1.包含头文件fstream
2.需要声明一个或多个ifstream的对象,并以自己喜欢的方式对其命名
3使用open()方法将ofstream的对象和文件关联起来,使用完文件后使用close()方法将其关闭
4.可以直接用fstream类的构造函数 如 ifstream fin("a.txt")
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("a.txt");
if(!fin.is_open())//如果文件被打开了,则将数据写入文件
{
char name[50];
fin.getline(name,50);
cout<<name;
fin.close();
}
else
{
cout<<"error"<<endl;
}
}
iostream提供了一个预先定义好的名为cin的istream的对象,所以cin有的方法 fin都可以用,比如fin.getline.
if_open()可以用来检测是否文件被打开了(可能由于访问权限问题,文件会打不开,也可能是文件不存在)。
eof()的方法可以用来判断是否到达文件末尾(到达文件末尾eof返回true)
fail()的方法可以来判断在输入的过程中是否出现类型不匹配的问题(发生类型不匹配fail返回true)
出现意外问题如文件受损或者硬盘故障,bad()会返回true。