zoukankan      html  css  js  c++  java
  • 文件读写

    和文件有关系的输入输出类主要在fstream.h这个头文件中被定义,在这个头文件中主要被定义了三个类,由这三个类控制对文件的各种输入输出操作,他们分别是ifstream、ofstream、fstream,其中fstream类是由iostream类派生而来,他们之间的继承关系见下图所示:

    打开并写入文件

    • ofstream  ofs
    • open 指定打开方式
    • isopen 判断是否打开成功
    • ofs << “数据”
    • ofs.close
    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    #include <fstream>      //读写文件
    
    void test01()
    {
        // 打开方式1:
        //ofstream ofs("./test.txt", ios::out | ios::trunc);  //在定义文件流对象时指定参数
        //打开方式2:
        ofstream ofs2;                                      //定义ofstream类(输出文件流类)对象
        ofs2.open("./test.txt", ios::out | ios::trunc);    //使文件流与test.txt文件建立关联
        if (!ofs2.is_open())        //判断是否打开成功
        {
            cout << "打开失败" << endl;
        }
    
        ofs2 << "姓名:xxx" << endl;
        ofs2 << "年龄: 18" << endl;
        ofs2 << "性别: 男" << endl;
    }
    
    int main()
    {
        test01();
        system("Pause");
        return 0;
    }

    结果:

    读取文件

    • ifstream  ifs
    • 指定打开方式 ios::in
    • isopen判断是否打开成功
    • 三种方式读取数据
    void test02()
    {
        ifstream ifs;
        ifs.open("./test.txt", ios::in);
        //判断是否打开成功
        if (!ifs.is_open())
        {
            cout << "打开失败" << endl;
        }
        //第一种方式
        char buf[1024];
        while (ifs >> buf) //按行读取
        {
            cout << buf << endl;
        }
    }
    void test03()
    {
        //第二种方式
        ifstream ifs;
        ifs.open("./test.txt", ios::in);
        char buf[1024];
        while (!ifs.eof()) //eof  读到文件末尾
        {
            ifs.getline(buf, sizeof(buf));
            cout << buf << endl;
        }
    }
    void test04()
    {
        //第三种 不同见 按单个字符读取
        ifstream ifs;
        ifs.open("./test.txt", ios::in);
        char c;
        while ( (c = ifs.get()) != EOF) //EOF 文件末尾
        {
            cout << c;
        }
    }

    结果:

    文件读写:https://blog.csdn.net/weixin_43918046/article/details/106367507

  • 相关阅读:
    ES6相关概念及新增语法
    正则表达式
    递归
    高阶函数和闭包
    严格模式
    this指向
    递归
    严格模式
    函数内部的this指向
    函数的定义和调用
  • 原文地址:https://www.cnblogs.com/yifengs/p/15186028.html
Copyright © 2011-2022 走看看