C++文本操作(读写文本文件/二进制文件)

C++文本操作(读写文本文件/二进制文件)

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

C++文本操作(读写文本文件/二进制文件)