• C++学习笔记四之文件操作


    一、文本文件---写文件

    1)写文件步骤

    2) 文件打开方式

    3)代码实例

    二、文本文件---读文件

    三、二进制文件---写文件

    四、二进制文件---读文件

    C++中对文件操作需要包含头文件<fstream>;

    文件类型分为两种:文本文件和二进制文件;

    操作文件的三大类:1.ofstream(写操作);2.ifstream(读操作);3.fstream(读写操作)。

    一、文本文件---写文件

    1)写文件步骤:

    ①包含头文件#include<fstream>

    ②创建流对象 ofstream ofs;

    ③打开文件ofs.open("path", 打开方式);

    ④写数据ofs<<"写入的数据";

    ⑤关闭文件ofs.close();

    2)文件打开方式

    注:文件打开方式可以配合使用,利用 | 操作符。例如:用二进制文件写文件ios::binary | ios::out。

    3)代码实例

    #include<iostream>
    #include<string>
    #include"A.h"
    #include<fstream>//1.包含头文件
    using namespace std;
    
    int main()
    {
        //②创建流对象 ofstream ofs;
        ofstream ofs;
    
        //③打开文件ofs.open("path", 打开方式);
        ofs.open("test.txt", ios::out);
    
        //④写数据ofs << "写入的数据";
        ofs << "hello world!";
    
        //⑤关闭文件ofs.close();
        ofs.close();
    
        system("pause");
        return 0;
    }

    二、文本文件---读文件

    1)读文件步骤

    ①包含头文件#include<fstream>

    ②创建流对象 ifstream ifs;

    ③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);

    ④读文件(四种方式读取)

    ⑤关闭文件ifs.close();

    2)代码实例

    #include<iostream>
    #include<string>
    #include"A.h"
    #include<fstream>//1.包含头文件
    using namespace std;
    
    int main()
    {
        //②创建流对象 ofstream ofs;
        ifstream ifs;
    
        //③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);
        ifs.open("test.txt", ios::in);
        if (!ifs.is_open())
        {
            cout << "文件打开失败!" << endl;
            system("pause");
            return 0;
        }
    
        //④读数据
        //法一
        /*char buf[1024] = { 0 };
        while (ifs >> buf)
        {
            cout << buf << endl;
        }*/
    
        //法二
        /*char buf[1024] = { 0 };
        while (ifs.getline(buf,sizeof(buf)))
        {
            cout << buf << endl;
        }*/
        //法三
        /*string str;
        while (getline(ifs, str))
        {
            cout << str << endl;
        }*/
        //法四
        char c;
        while ((c=ifs.get())!=EOF)//EOF:end of file
        {
            cout << c << endl;
        }
    
        //⑤关闭文件ofs.close();
        ifs.close();
    
        system("pause");
        return 0;
    }

    三、二进制文件---写文件

    ①打开方式指定为  ios::binary | ios::out ;

    ②调用write函数写文件:ostream &write(const char* buf, int len);

    四、二进制文件---读文件

    ①读文件调用函数read:istream &read(char* buf, int len);

  • 相关阅读:
    eclipse用法和技巧
    eclipse常用快捷键集锦
    移动端input的虚拟键盘影响布局
    使用github page + Hexo搭建个人博客折腾记
    javascript数组的排序(sort,冒泡)
    响应式布局与媒体查询
    css属性选择器诸如Class^=,Class*= ,Class$=释义
    怎么预览 GitHub 项目里的网页或 Demo
    常见浏览器的兼容问题(一)
    jQuery常用交互效果
  • 原文地址:https://www.cnblogs.com/mango1997/p/14548799.html
Copyright © 2020-2023  润新知