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();
    }

  • 相关阅读:
    [转载] 关于mkvtoolnix批量处理的
    转载:JMeter压力测试入门教程[图文]
    分享 stormzhang的Andoid学习之路
    Sublime Text 2 插件
    PHP 操作SQLite
    curl 远程下载图片
    centos lamp 配置
    php 例子 如何转换ISO8601为 utc时间
    php 常用 常量集合
    php 文档操作
  • 原文地址:https://www.cnblogs.com/ASsss/p/14418139.html
Copyright © 2011-2022 走看看