【IO】IO库(二)文件操作

C++IO库继承图

在这里插入图片描述

读写文件

  • C++提供了ifstream、ofstream、fstream类供我们使用来进行文件读写操作。其中ifstream用于读文件,ofstream用于写文件、fstream可用于读写文件。
文件打开与关闭
  • 可以调用open和close函数进行文件打开与关闭操作
#include <iostream>
#include <fstream>
#include <string>


int main() {
    using namespace std;
    string file = "hello.txt";

    fstream fp;
    fp.open(file);//打开文件
    if(fp){
        fp << "hello world...";
        fp.close();//关闭文件
    } else{
        cerr<<"fail to open file"<<endl;
    }
    return 0;
}
文件模式
  • 文件模式有以下几种
    /*
     * in  读
     * out 写
     * app 每次写之前定位到文件末尾
     * ate 打开文件后立即定位到文件末尾
     * binary 以二进制方式打开
     */

    fp.open(file,fstream::in|fstream::out|fstream::app);//打开文件
资源管理
  • 每次打开文件后要记得close释放资源
  • 当文件对象被销毁时,会自动调用close函数释放资源
读写文件

有两种方法进行读写文件,一种利用重载的<<和>>运算符。一种利用read()和wirte()函数

  • 利用<<和>>运算符时,写入的是字符数据,也就是说,会将要写入的数据看做字符。
#include <iostream>
#include <fstream>
#include <string>
int main() {
    using namespace std;

    string fileName = "hello.txt";
    fstream fp;
    fp.open(fileName, fstream::out | fstream::trunc);
    if (fp) {
        for (int j = 0; j < 5; ++j) {//为了便于查看,写入五次相同的数据
            int i = 123;
            fp << i;//这里写入的是字符1和字符2和字符3,利用for写入了五次
        }
        fp.close();
    } else {
        cerr << "fail to open file" << endl;
    }
    return 0;
}

下面是写入后的文件(vim二进制打开文件,利用16进制查看,每个字节一组显示)。可以看到第一个字节是十六进制的31,也就是49(1的assic码是49),后面以此类推。
在这里插入图片描述

  • 利用write()函数写入,会将数据的byte存储写入文件。
basic_ostream& write( const char_type* s, std::streamsize count );

Parameters
s	-	pointer to the character string to write
count	-	number of characters to write

Return value    *this
basic_istream& read( char_type* s, std::streamsize count );

Parameters
s	-	pointer to the character array to store the characters to
count	-	number of characters to read

Return value    *this
#include <iostream>
#include <fstream>
#include <string>
int main() {
    using namespace std;

    string fileName = "hello.txt";
    fstream fp;
    fp.open(fileName, fstream::out | fstream::trunc);
    if (fp) {
        for (int j = 0; j < 5; ++j) {//为了便于查看,写入五次相同的数据
            int i = 16;
            fp.write((char *) &i, sizeof(i));//这里每次写入一个int数据(4个字节)
        }
        fp.close();
    } else {
        cerr << "fail to open file" << endl;
    }
    return 0;
}

下面是写入后的文件(vim二进制打开文件,利用16进制查看,每个字节一组显示)。可以看到一共20个字节(4*5)。前四个字节是int型数据1的存储,以此类推
在这里插入图片描述

  • 总结:个人感觉write()和read()函数用起来更加方便,想写入任何类型的变量都很方便。只需要将变量地址转换为char *类型的地址即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值