需要包含的头文件<fstream>
以下只列出核心代码,其它基本头文件自己添加
需要注意不管是读文件或者是写问件,结束后都要调用: 文件.clear()清除所有的标志位,文件.close()关闭文件
读文件流:
例如打开桌面的1.txt文件并读取数据
1.单个读取:
ifstream ifen;
char str[50];
ifen.open("C:\\Users\\lai\\Desktop\\1.txt");
ifen>>str;
cout<<str<<endl;
2.按行读取:
ifstream ifen;
string buffer;
char str[50];
ifen.open("C:\\Users\\lai\\Desktop\\1.txt");
while(ifen.is_open())//判断文件是否已经打开
{
getline(ifen,buffer);
//也可以
//ifen.getline(str,50);
//cout<<str<<endl;
cout<<buffer<<endl;
}
//如果按行读入的文件每行是( Bob,Dog)这样的布局则可以使用下面的方法来分别读取Bob和Dog
//故分别定义以下两个函数用于提取一个string类型的字符串中想要的字符串
string getfname(string fname)
{
string r;
size_t index = fname.find(',');//获取逗号所在的位置
if (index != -1)
r = fname.substr(0, index); //从0位置开始到index位置前面取字符串
else
r = "-1";
return r;
}
string getlname(string lname)//类似上面的函数
{
string r;
size_t index = lname.find(',');
if (index != -1)
r = lname.substr(index+1, lname.length()-1);
else
r =" -1";
return r;
}
//即如果字符串str="Bob,Dog"则通过getfname(str)可以提取出Bob,同理用getlname(str)可以提取出Dog字符
写文件流:
string str=",";
vector<int>v;
int dim[]={1,2,3,4,5,6,7,8,9};
v.assign(dim.dim+9);
ofstream of("C:\\Users\\lai\\Desktop\\1.txt",ios::app);
of <<endl<< "开始写入数据"<<endl;
copy(v.begin(), v.end(), ostream_iterator<int> (of, str.c_str()));
个人笔记有待改善、、、、、、、