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

 

posted @ 2021-01-15 12:11  y0um  阅读(76)  评论(0编辑  收藏  举报

新人优惠服务器