zoukankan      html  css  js  c++  java
  • C++文本操作(读写文本文件/二进制文件)

     

    #include<iostream>
    //包含头文件
    #include<fstream>
    using namespace std;
    
    //读写文件
    void test1() {
        //创建流对象
        ofstream ofs;
        //指定打开方式
        ofs.open("test.txt", ios::out);
        //写内容
        ofs << "姓名: 张三"<<endl;
        ofs << "性别: 男" << endl;
        ofs << "身高: 180" << endl;
        //关闭文件
        ofs.close();
    }
    int main() {
        test1();
        system("pause");
    }

    读文件

    void test2() {
        //1.包含头文件
    
        //2.创建流对象
        ifstream ifs;
        //3.打开文件 并判断是否打开成功
        ifs.open("test.txt", ios::in);
        if (!ifs.is_open())
        {
            cout << "打开文件失败" << endl;
        }
        //4.读数据
        //第一种方法
        /*char buf[1024];
        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;
        }*/
        //5.关闭文件
        ifs.close();
    }

    写二进制文件

    void test3() {
        //创建流对象
        ofstream ofs;
        //打开文件 
        ofs.open("person.txt", ios::out | ios::binary);
        //声明对象
        Person p = { "李四",18 };
        //写入文件
        ofs.write((const char*)&p, sizeof(Person));
        //关闭文件
        ofs.close();
    }

     读二进制文件

    //二进制读文件
    void test4() {
        ifstream ifs;
        ifs.open("person.txt", ios::in | ios::binary);
        if (!ifs.is_open())
        {
            cout << "打开文件失败" << endl;
            return;
        }
    
        Person p;
        ifs.read((char*)&p, sizeof(Person));
        cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
    
        ifs.close();
    }

  • 相关阅读:
    LayoutInflater(布局服务)
    FOTA升级
    APK安装过程及原理详解
    Context类型
    Android应用的persistent属性
    Notification(状态栏通知)详解
    Handler消息传递机制浅析
    Selenium HTMLTestRunner 无法生成测试报告的总结
    【python】远程使用rsa登录sftp,上传下载文件
    02.性能测试中的指标
  • 原文地址:https://www.cnblogs.com/ASsss/p/14418139.html
Copyright © 2011-2022 走看看