顺序访问文件
文本文件和二进制文件进行读/写操作。
1.文本文件读/写操作
例如: 向文件mufile.text写入一个整数,一个浮点数以及一个字符串。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream out("myflie.txt"); //创建流对象并打开文件
if(!out) //判断文件是否成功打开
{
cout<<"can't open file myfile.txt \n";
renturn 1;
}
out <<123<<" "<<1<<" "<<"They are boys"<<endl; //向文件写入数据
out.close(); //关闭文件
return 0;
}
读入数据:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a;
double b;
char ch,str1[20],str2[20];
ifstream in("myfie.txt"); //创建流对象并打开文件
if(!in is_open) //判断文件是否成功打开
{
cout<<"can't open file!\n"<<endl;
return 1;
}
in>>a>>b>>ch>>str1;
cout<<a<<endl;
cout<<b<<endl:
cout<<ch<<endl;
cout<<str1<<endl;
in.getline(str2.20);
cout<<str2<<endl;
return 0;
}
二进制文件的读/写
如果在代开文件时指定了模式 iOS::binary, 就以二进制方式打开了文件。通常有两种方法可以从文件读取或者写入二进制数据: 一种是使用函数get()从文件中读取一个字符,使用函数 put()向文件中写入一个字符;另一种是使用流库中的数据块输入和输出函数read()和write();(我们通常是使用read()跟write())
:
istream &istream::read(char *buff ,streamsize num);
ostream &ostream::write(char *buf,streamsize num);