文件的输入输出 C++

1、3种文件流:fstream、ifstream、ofstream。其都定义在fstream.h。

2、建立流:

fstream both;
ifstream   in ;
ofstream out;
3、打开流:
void open(const unsigned char *,int mode,int access=filebuf::openprot)
第一个参数为文件名,如"C://test.tex"。第二个参数mode由以下几种:

ios::app  //打开时指针移到文件最后,用于输出,且文件必须存在,不存在会打开错误。
ios::in   //用于读取文件,文件必须存在。
ios::out  //用于输出。
ios::binary  //以二进制方式打开文件,缺省时是以文本。
ios::nocreat //文件不存在将报错,缺省时不会报错。
ios::noreplace //文件存在报错。
ios::ate  //查找文件
ios::trunc  //文件存在,则原同名文件被删除
第三个参数access有几种:0   普通文件 ,1 只读文件 ,2 隐含文件  ,4  系统文件,8 备份文件 。

注意:打开ifstream流缺省为ios::in,0;ofstream流缺省为ios::out,0。除了用open打开,还可以使用构造函数打开,如

ofstream out("C://test.txt");
if(!out);//打开失败检测处理
{
      cout <<"can't open file \n";
}
4、关闭: 
out.close();
5、文件读写:如
out<<" "<<123<<"file";//写 123file到文件上
char str[80];
in>>str;//读到str数组中

6、二进制文件的读写:

6.1、

ifstream &get(char &ch);//读入一个字符到ch地址中
ofstream &put(char ch);//将ch写入流中并返回流

6.2、
ifstream &read(unsigned char *buf,int num);//从流读出num字节到buf指向的缓冲区,注意*buf的类型,常用到强制转换(unsigned char *)
ofstream &write(const unsigend char *buf, int num);//把num字节的buf中的数据写入到流
//例子:
int i;
in.read((unsigned char *)&i,sizeof(int));
int j=1234;
out.write((const char *) &j,sizeof(int));
//结构类型读写
struct atypr{
};
struct atypr a;
out.write((const char *)&a,sizeof(struct stypr));
in.read((char*)&a,sizeof(struct atypr));

7、检测文件结束:三种方法:

//法一
if(!in.eof())
{
    ```
}
//法2
if(!in){}//检测该流对象是否为零
//法3
while(in.get(c))
{
   cout<<c;
}//较通用,返回值为零则到达文件尾





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值