zoukankan      html  css  js  c++  java
  • C++文件操作——二进制读写文件

    二进制的方式进行读写操作

    ios::binary

    #include<iostream>
    #include<fstream>
    using namespace std;
    二进制文件,写文件
    class person{
    public:
    char m_Name[64];
    int m_age;
    }
    void test(){
    1.包含头文件
    2.创建新文件
    ofstream ofs;
    3.打开文件
    ofs.open("person.txt",ios::out|ios::binary);
    person p={"关羽",23};
    4.写文件
    ofs.write(const char *)&p,sizeof(person);

    5.关闭
    ofs.close();
    }

    =============================================
    二进制方式
    读文件

    #include<iostream>
    #include<fstream>
    #include<string>

    using namespace std;

    class person{
    public:

    string m_Name[64];
    int m_age;
    }

    void test(){
    ifstream ifs;

    ifs.open("person.txt",ios::in|ios::binary);
    if(!ifs.is_open()){
    cout<<"没有此文件"<<endl;
    return ;
    }
    person p;

    ifs.read((char *)&p,sizeof(p));
    cout <<"p.name=" <<p.name <<","<<"p.age="<< p.age << endl;
    ifs.close();
    }

    昨夜西风凋碧树,独上高楼,望尽天涯路 衣带渐宽终不悔,为伊消得人憔悴 众里寻他千百度。蓦然回首,那人却在,灯火阑珊处
  • 相关阅读:
    spring retry注解
    安装mongodb并配置
    spring boot Hello World
    Linux命令echo
    Linux vi命令
    查看linux是ubuntu还是centos
    Linux系统时间, 硬件BIOS时间的校准与同步
    MySQL优化查询 5.7版本
    战略由谁来制定
    VS2015快捷键
  • 原文地址:https://www.cnblogs.com/X404/p/14375435.html
Copyright © 2011-2022 走看看