【C++】读写文件

  • 简单的读写文件方法
  • 直接上代码
#include<iostream>
#include<fstream>    //文件操作必用头文件
using namespace std;


/*
文件类型:
1.文本文件:ASCLL
2.二进制文件: 顾名思义
*/

/*
1.ofstream:写
2.ifstream:读
3.fstream:读写
*/


/*
文本文件
写步骤:
1.包含头文件  #include<fstream>
2.创建流对象  ofstream ofs;
3.打开文件  ofs.open("文件路径",打开方式);
4.写数据 ofs<<"写入数据";
5.关闭文件 ofs.close();

读步骤:
1.包含头文件  #include<fstream>
2.创建流对象 ifstream ifs;
3.打开文件并判断文件是否打开成功  ifs.open("文件路径","打开方式");
4.读数据  三种方式读取即可
5.关闭文件 ifs.close();
*/

/*
文件打开方式:较常用
ios::in   为读文件而打开文件,而且文件必须已经存在
ios::out  为写文件而打开文件
ios::trun  若文件已经存在,则清空其内容在写入,若文件不存在,则创建该文件
ios::binary  以二进制的方式打开文件
ios::app 将数据添加至文件尾部,文件必须已经存在
*/

void test_write()  //文本文件写
{
    ofstream obj;
    cout<<"--------写文件--------"<<endl;
    obj.open("C:/Users/10369/Desktop/test.txt", ios::out);

    obj<<"秋山刀名鱼"<<endl;
    obj<<"求三连"<<endl;
    obj.close();

}

void test_read()   //文本文件读
{
    ifstream obj;
    cout<<"--------读文件--------"<<endl;
    obj.open("C:/Users/10369/Desktop/test.txt", ios::in);
    if( !obj.is_open() )
    {
        cout<<"文件打开失败!"<<endl;
        return;
    }
    else
    {
        //第一种
        /*
        char buf[1024] = { 0 };
        while( obj>>buf )
        {
            cout<<buf<<endl;
        }
        */
       //第二种
       /*
        char buf[1024] = { 0 };
        while( obj.getline( buf, sizeof(buf)) )
        {
            cout<<buf<<endl;
        }
        */
       //第三种
       string buf;
        while( getline(obj, buf))
        {
            cout<<buf<<endl;
        }
        obj.close();
    }
    
}

class person{
    public:
        int _num;
};

void test_bin_write()   //二进制文件写
{
    ofstream obj;
    obj.open("C:/Users/10369/Desktop/test_bin.txt", ios::out | ios::binary);
    person temp = {345352};
    //ostream& write(const char *p, int len);
    obj.write((const char *)&temp, sizeof(person));
    obj.close();
}


void test_bin_read()  //二进制文件读
{
    ifstream obj;
    obj.open("C:/Users/10369/Desktop/test_bin.txt", ios::in | ios::binary);
    if( !obj.is_open() )
    {
        cout<<"文件打开失败!"<<endl;
    }
    else
    {
        person temp;
        obj.read((char*)&temp, sizeof(person));
        cout<<"读取数值:"<<temp._num<<endl;
        obj.close();
    }
    
}

int main()
{
    test_write();
    test_read();
    test_bin_write();
    test_bin_read();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋山刀名鱼丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值