文件流有点类似标准输出和标准输入;文件类型可以分为两种:文件流包括文本文件和二进制文件,生活中大量的信息都是用文本文件来保存的,二进制文件保存的只是二进制数据,利用二进制模式,你可以操作图像等文件。
ifstream – 从已有的文件读
ofstream – 向文件写内容
fstream - 打开文件供读写
一,写文件ofstream
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
void main()
{
//打开文件,使其对应输出流out
ofstream out("F:\\vs2010\\hello world\\Test.txt");
if(!out)
{
cout<<"不可以打开文件"<<endl;
exit(0);
}
//写入文件
out<<"hello world"<<endl;//直接将字符串写入文件
cout<<"hello world"<<endl;
char ch;
cout<<"请输入将要写入文件的字符,直到回车结束:";
while( cin.get(ch) )//从键盘中输入数据到文件
{
if(ch=='\n') break;
out.put(ch);
cout.put(ch);
}
//关闭文件
out.close();
}
二,读文件ifstream
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
void main()
{
//打开文件,使其对应输出流in
ifstream in("F:\\vs2010\\hello world\\Test.txt");
if(!in)
{
cout<<"不可以打开文件"<<endl;
exit(0);
}
//读文件
string str;
getline(in,str);
cout<<str<<endl;
char ch;
while(in.get(ch))
{
cout.put(ch);
}
//关闭文件
in.close();
}
三,文件流fstream
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
void main()
{
fstream file("F:\\vs2010\\hello world\\FILE.txt",ios::out);//创建文件流file,打开方式为out,所以此时为输出文件流
if (!file)
{
cout<<"不能打开文件"<<endl;
exit(0);
}
file<<"hello world"<<12<<" "<<'12'<<'c'<<endl;
file.close();
file.open("F:\\vs2010\\hello world\\FILE.txt",ios::in);//打开方式为in,所以为输入文件流
string str;
getline(file,str);
cout<<str<<endl;
file.close();
}
四,其他
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
void main()
{
ifstream in("F:\\vs2010\\hello world\\Test.txt");//打开文件Test.txt,将其对应为输入文件流in
ofstream out("F:\\vs2010\\hello world\\Out.txt");//打开文件Out.txt,将其对应为输出文件流out
//对文件的操作将变为对文件流in和out的操作
for(string str;getline(in,str); )//getline(in,str):从in中读入一行数据放入str中,整行整行读入
{
out<<str<<endl;//将str和endl输出到out中,即输出到文件Out.txt中
cout<<str<<endl;//将str和endl输出到黑框中
}
}
实现了文件的复制,将创建一个新的文件Out.txt,该文件复制了Text.txt中的内容,且
打开文件还可以用以下方法:
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
void main()
{
ofstream out;
out.open("F:\\vs2010\\hello world\\File.txt");
out<<"hello world"<<endl<<75<<" "<<"75"<<endl;
cout<<"hello world"<<endl<<75<<" "<<"75"<<endl;
out.close();
}