• 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; 
    }
  • 相关阅读:
    结对编程作业
    软件工程网络15个人阅读作业1
    Java课程设计——学生基本信息管理
    JAVA课程设计
    201521123102 《Java程序设计》第12周学习总结
    201521123102 《Java程序设计》第11周学习总结
    201521123102 《Java程序设计》第9周学习总结
    个人作业5——软工个人总结
    alpha阶段个人总结
    案例分析
  • 原文地址:https://www.cnblogs.com/cou1d/p/14281432.html
Copyright © 2020-2023  润新知