4. 磁盘文件的打开和关闭
打开
ofstream outfile;
if(outfile.open("f1.data",ios::app)==0) // 打开
cout<<"打开失败!";
……………………
outfile.close(); //关闭
5. 文件写入
#include <fstream>
#include <iostream>
#include <string> //一定不能少了,否则报错 error C2679
using namespace std;
int main()
{
string str;
ofstream out("d.txt",ios::out); //等价于ofstream out("d.txt")
if(!out) //若打开失败,out返回0值
{
cerr<<"打开失败!"<<endl;
exit(0);
}
str="床前明月光/n疑是地上霜/n举头望明月/n低头思故乡/n";
out<<str<<endl;
return 0;
}
6. 读文件到控制台
#include <fstream>
#include <iostream>
#include<string>
using namespace std;
int main()
{
ifstream infile("d://new//d.txt",ios::in); //定义输入文件的流对象,以输入方式打开磁盘文件d.txt,第二个参数可去
if(!infile)
{
cerr<<"打开失败!"<<endl;
exit(1);
}
for(string str;getline(infile,str);) //逐行打开并逐行显示,因此在循环中实现
cout<<str<<"/n";
infile.close();
return 0;
}
或把 for(string str;getline(in,str);)
cout<<str<<"/n";
两句改为 string str;
while(getline(in,str))
cout<<str<<"/n";
7. 文件复制
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream in("d.txt");
if(!in)
{
cerr<<"打开源文件失败!"<<endl;
exit(1);
}
ofstream out("b.txt");
if(!out)
{
cerr<<"打开目的文件失败!"<<endl;
exit(1);
}
for(string str;getline(in,str);)
out<<str<<endl; //注意是out
cout<<"文件复制成功!"<<endl;
in.close();
out.close();
return 0;
}
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/Deutschester/archive/2009/06/24/4295723.aspx