文件操作

环境:ide:Mac+clion

视频链接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5

文件操作

文件操作:持久化数据。
文件存储形式:文本文件/二进制文件
读文件:ifsteam 读文件
写文件:ofstream 输出到文件中。
读写操作:fsteam

写文件步骤:

1.包含头文件 #include <fstream>
2.创建流对象。
3.打开文件。ios::in 读文件 ios::out 写文件 ios::binary 二进制
4.写文件。
5.关闭流。

#include <fstream> //包含头文件#include<ostream>
void writeFile(){
    ofstream  ofs;//创建流对象
    ofs.open("info.txt",ios::out);
    ofs<<"姓名:sheik"<<endl;
    ofs<<"性别:male"<<endl;
    ofs<<"年龄:20"<<endl;
    ofs.close();
}
void readFile() {
    ifstream ifs;//创建流对象。
    ifs.open("info.txt",ios::in);
    if(!ifs.is_open()){    //判断文件是否打开成功。
        cout << "文件打开失败。"<<endl;
        return;
    }
    //4.四种方式读文件。
    //第一种方式:
//    char buf[1024] = {0};
//    while(ifs >> buf){
//        cout << buf<<endl;
//    }

//第二种方式:
    char buf[1024] = {0};
    while(ifs.getline(buf,sizeof (buf))){
        cout << buf<< endl;
    }

//第三种
//    string buf;
//    while(getline(ifs,buf)){
//        cout << buf<<endl;
//    }

//第四种:EOF 文件尾部的标志。
//    char c;
//    while((c=ifs.get())!= EOF){
//        cout << c<<endl;
//    }
    //5.关闭流。
    ifs.close();
}

通过二进制的方式读写:

class Person{
public:
    string m_Name;
    int m_Age;
};

void writeBinary(){
    ofstream ofs;
    ofs.open("bean.txt",ios::out | ios::binary);
    Person person;
    person.m_Name = "张三";
    person.m_Age = 18;
    ofs.write((const char *)&person,sizeof (person));
    ofs.close();
}

void readBinary(){
    ifstream  ifs;
    ifs.open("bean.txt",ios::in | ios::binary);
    if (!ifs.is_open()){
        cout << "文件打开失败!"<<endl;
        return ;
    }
//    char ch;
//    ifs >>ch;
//    if (!ifs.eof()){
//        cout << "文件不为空!"<<endl;
//        //return ;
//    }
    Person person ;
    ifs.read((char *)&person,sizeof (person));
    cout << person.m_Name << "," << person.m_Age<<endl;
    ifs.close();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载(https://www.cnblogs.com/MrYuan/p/5383408.html) 基于C的文件操...
    送分童子笑嘻嘻阅读 477评论 0 0
  • 文件基本概念和文件流类 文件的概念 从不同的角度来看待文件就可以得到不同的文件分类。C++根据文件数据的编码方式不...
    silasjs阅读 615评论 0 1
  • 程序运行时产生的数据都存储内存里面,一旦程序运行结束,内存里面的数据就会消失。如果我们想要持久保留一些重要数据,就...
    殷超锋阅读 422评论 2 3
  • 文件操作 文件基本概念 根据文件数据的编码方式不同可以分为: 文本文件 二进制文件 根据存取方式不同分为: 顺序存...
    陈_MY阅读 566评论 0 0
  • c++文件操作: 文件操作三大步(逻辑如下):1、打开文件2、读写文件3、关闭文件 介绍下头文件: #includ...
    北影拼搏阅读 767评论 0 2