C++中级-文件读写

#include <iostream>
#include <string>
#include <fstream>

using namespace std;



/*
        模式标志       描述
        ios::app    追加模式。所有写入都追加到文件末尾。
        ios::ate    文件打开后定位到文件末尾。
        ios::in        打开文件用于读取。
        ios::out    打开文件用于写入。
        ios::trunc    如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。
*/

class CStudent
{
public:
    char szName[20];
    int age;
};

class File{
public:
    
    void FileWrite(string args) {
        //1.写文件对象创建
        ofstream obj1;
        //2.选择写out模式标志
        obj1.open("./t1.txt",ios::out);
        //3.输入内容
        obj1 << args;
        //4.关闭文件句柄
        obj1.close();
    };

    void FileRead(string args) {
        //1.读文件对象创建
        ifstream obj;
        //2.选择读in模式标志
        obj.open(args, ios::in);
        //2.读内容
        if (obj)
        {
            string buffer;
            while (getline(obj,buffer))
            {
                cout << buffer << endl;
            }
        }
        else
        {
            cout << "Not file!" << endl;
        };
        //关闭句柄
        obj.close();
    };
    
    void BinFileWrite() {
        CStudent s;
        ofstream outFile("students.dat", ios::out | ios::binary);
        while (cin >> s.szName >> s.age)
            outFile.write((char*)&s, sizeof(s));
        outFile.close();
    };

    void BinFileRead() {
        CStudent s;
        ifstream inFile("students.dat", ios::in | ios::binary); //二进制读方式打开
        if (!inFile) {
            cout << "error" << endl;
            return;
        }
        while (inFile.read((char*)&s, sizeof(s))) { //一直读到文件结束
            int readedBytes = inFile.gcount(); //看刚才读了多少字节
            cout << s.szName << " " << s.age << endl;
        }
        inFile.close();
    };
};



int main() { 
    //File f;
    //f.FileWrite("Success fule");

    //File f;
    //f.FileRead("./t1.txt");

    //File f1;
    //f1.BinFileWrite(R"(We are the champion)");

    //File f;
    //f.BinFileRead();

    return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值