c++的fstream

fstream 支持<< 和>> 操作符

C语言的文件操作

函数fopen()将一个文件和一个流关联起来。并初始化一个FILE对象,这个对象包括一个指向缓冲区的指针,文件位置指示器,以及指示错误和文件结尾情况的标识。

#include<stdio.h>
#include<stdbool.h>
_bool isreadwriteable(const char *filename){
FILE *fp=fopen(filename,"r+");//打开一个文件用于读写
if(!fp=null){
fclose(fp);
return true;
}else
return false;
}

C++文件操作

直接对流对象进行操作

fstream foi("........", ios::in|ios::out);

文件的写操作

包括一个

write (const *char message, int size);
#include<fiostream.h>
int main(){
	ofstream out("filename.txt");
    if(out.is_open()){
        out<<"jion in the file.";
        out.close();
    } 
}
文件的读操作
#include<iostream>
#include<fstream.h>
#include<stdlib.h>
int main(){
    char buffer[100];
    ifstream in("filename.txt");
    if(in.is_open()){
        while(in.eof()){
            in.getline(buffer,99);
            cout<<buffer<<endl;
        }
    }
}

open 函数

void open(const char *filename, ios::openmode)

open mode

ios::app		//以追加的模式打开文件
ios::ate 		//文件打开后定位到文件尾,ios::app就包含此属性
ios::binary		//以二进制的方式打开文件,缺省的方式就是文本方式。
ios::in			//文件以输入方式打开(文件数据输入到内存)
ios::out		//文件以输出方式打开(内存数据输出到文件)
ios::nocreate 	//不建立文件,所以文件不存在时打开失败
ios::noreplace	//不覆盖文件,所以打开文件时 如果文件存在 失败
ios::trunc		//如果文件存在,文件长度设为0

状态标识符

一些验证流的状态的成员函数(返回值为 bool 类型)

is_open()		//文件是否打开
bad()			//读写过程中是否出错(操作对象没有打开,写入设备没有空间)
fail()			//读写过程中是否出错(操作对象没有打开,写入设备没有空间,格式错误)
eof()			//读文件达到文件末尾,返回true
good()			//以上任何一个返回true,这个就返回false

获得和设置流指针

//对于所有的输入输出流都至少有一个指针,指向下一个要操作的位置
ofstream put_point
ifstream get_point

//获取流指针的位置
tellg()			//获取输入流指针的位置(return long)
tellp()			//获取输出流指针的位置

//设置指针位置
seekg(long position) 		//设置输入流指针的位置
seekp(long position)		//设置输出流指针的位置

example:

#include<fstream>

int main(){
    std::ofstream out;
    out.open("hello.txt");
    out<<"hello world";
    long pos=out.tellp();
    out.seekp(pos-3);
    out<<" how beautiful";
    
    out.close();
}
读取文件内容
#include<iostream>
#include<fstream>

int main(){
    std::ifstream in;
    in.open("hello.txt");
    char x =in.get();//也可以是getline() 或者 >>
    
    while(in.good()){
        std::cout<<x;
        c=in.get();
    }
    in.close();

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值