• C++中的文件写入和读取(文本文件方式,二进制方式)


    一、文件的写入

    1 // 写文件操作  文本文件写入
    2 ofstream ofs;
    3 ofs.open("temp.txt",ios::out);
    4 ofs << "姓名:张三" << endl;
    5 ofs << "性别:男" << endl;
    6 ofs << "学校:楚雄师范学院" << endl;
    7 ofs.close();
    //写文件  二进制方式操作
    class Person
    {
    public:
        char m_name[64];
        int m_age;
    };
    void main()
    {
        ofstream ofs;
        ofs.open("Person.txt",ios::out | ios::binary);
        Person p = { "张三",18 };
        ofs.write((const char *)&p, sizeof(Person));
        ofs.close();
    
    }

    二、文件的读取(5中方式)

    1~4  文本文件读取

    5      二进制文件读取

    方式1:

    1     //1.
    2     ifstream ifs;
    3     ifs.open("temp.txt", ios::in);
    4     char buf1[1024] = { 0 };
    5     while (ifs >> buf1)
    6     {
    7         cout << buf1 << endl;
    8     }
    9     ifs.close();

    方式2:

    1       2. 
    2     ifstream ifs;
    3     ifs.open("temp.txt",ios::in);
    4     char buf2[1024] = { 1 };
    5     while (ifs.getline(buf2,sizeof(buf2)))
    6     {
    7         cout << buf2 << endl;
    8     }
    9     ifs.close();

    方式3:

    1     3.
    2     ifstream ifs;
    3     ifs.open("temp.txt",ios::in);
    4     string str;
    5     while (getline(ifs,str))
    6     {
    7         cout << str << endl;
    8     }
    9     ifs.close();

    方式4(不推荐):

        //4.(不推荐)
        ifstream ifs;
        ifs.open("temp.txt",ios::in);
        if (! ifs.is_open())
        {
            return 0;
        }
        char ch;
        while (( ch = ifs.get())  != EOF)
        {
            cout << ch;
        }
        ifs.close();

     方式5:

        // 读文件   二进制方式
        ifstream ifs;
        ifs.open("Person.txt",ios::in | ios::binary);
        if (! ifs.is_open())
        {
            return 0;
        }
        Person p2;
        ifs.read((char *)&p2, sizeof(Person));
        ifs.close();
        cout << p2.m_name << endl;
        cout << p2.m_age << endl;
  • 相关阅读:
    pgpoolII3.1 的内存泄漏(二)
    iOS 开发的一些网址
    ios开发必备第三方库
    iOS截屏方法
    ios开发第三方库cocoapods安装
    iOS开发知识点总结
    iOS开发文件夹Copy items if needed
    iOS开源库最全的整理
    iOS图标抖动效果
    iOS 加密的3种方法
  • 原文地址:https://www.cnblogs.com/spiderljx/p/13130809.html
Copyright © 2020-2023  润新知