c++文件输入与输出

基于流的文件IO

头文件
ofstream : 写文件
ifstream : 读文件
fstream : 读写文件

using namespace std;
//打开文件
std::ifstream fin("xxx.txt");
//std::ifstream fin;
//fin.open("xxx.txt");
std::ofstream fout("xxxx.txt");
if (!fin.is_open())  //判断文件是否打开成功
{
    cout << "打开文件异常" << endl;
    fin.clear();
}
//从文件读取一个字符
char ch;
fin >> ch;              //read a character from the file

char buf[80];
fin >> buf;             //read a word from the file
fin.getline(buf, 80);   //read a line from the file

string line;
getline(fin, line);     //read from a file to a string object
fout<< line;				

fout.close();
fin.close();            
fin.clear();            //reset fin
  • 文件模式
    将流与文件关联时(无论所雇佣文件名初始化文件流对象,还是使用open()方法),都可以指定文件模式第二个参数:
    ifstream fin(“xxxxx.txt”,openMode1);
    ofstream fout();
    fout.open(“xxxxx.txt”,openMode2);
常量含义
ios_base::in打开文件,以便读取
ios_base::out打开文件,以便写入
ios_base::ate打开文件,并移到文件尾
ios_base::app追加到文件尾
ios_base::trunc如果文件存在,截断文件(清空旧文件)
ios_base::binary二进制文件

ifstream open()方法和构造函数用ios_base::in(打开文件以读取)作为模式参数的默认值,而ofstream open()方法和构造函数用 ios_base::out|ios_base::trunc(打开文件,以写入并截断文件)作为默认参数。位运算符or(|)用于将两个位值合并成为一个可用于设置两个位的值。

  • c++mode与cmode对应关系
c++模式c模式含义
ios_base::in“r”打开以读取
ios_base::out|ios_base::trunc“w”打开以写入,如果已存在,则覆盖
ios_base::out|ios_base::app“a”打开以写入,只追加
ios_base::out|ios_base::out“r+”打开以读写,在文件允许的位置写入
ios_base::out|ios_base::out|ios_base::trunc“w+”打开以读写,如果已存在,首先覆盖
c++mode|ios_base::binary“cmode”+“b”以c++mode(或相应cmode)和二进制模式打开;例如:ios_base::in|ios_base::binary成为"rb"
c++mode|ios_base::ate“cmode”以指定模式打开,并移到文件尾。C是使用一个独立的函数调用,而不是模式编码。例如:ios_base::in|ios_base::ate 被转换为"r"模式打开,然后调用fseek(file,0,SEEK_END)

注意:ios_base::ate和ios_base::app都将文件指针指向打开的文件末尾。二者的区别在于,ios_base::app模式只允许将数据添加到文件末尾,而ios_base::ate模式是将指针放到文件尾。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值