c++教程2021-6-19学习笔记

#include <fstream>//文件读写的头文件。
/**
 *文件操作:持久化数据。
 * 文件存储形式:文本文件/二进制文件
 */

/**
 * 读文件:ifsteam 读文件
 * 写文件:ofstream 输出到文件中。
 * 读写操作:fsteam
 */


//写文件步骤:
//1.包含头文件 #include <fstream>
//2.创建流对象。
//3.打开文件。ios::in 读文件  ios::out 写文件 ios::binary 二进制
//4.写文件。
//5.关闭流。

void writeFile() {
    //1.包含头文件 #include <fstream>
    //2.创建流对象。
    ofstream ofs;
    //3.打开文件。ios::in 读文件  ios::out 写文件 ios::binary 二进制
    ofs.open("wirte.txt",ios::out);
    //4.写文件。
    ofs<<"姓名:张三"<<endl;
    ofs<<"性别:男"<<endl;
    ofs<<"年龄:18"<<endl;
    //5.关闭流。
    ofs.close();
}
void readFile() {
    //1.包含头文件 #include <fstream>
    //2.创建流对象。
    ifstream ifs;
    //3.打开文件。
    ifs.open("wirte.txt",ios::in);
    //判断文件是否打开成功。
    if(!ifs.is_open()){
        cout << "文件打开失败。"<<endl;
        return;
    }
    //4.四种方式读文件。
    //第一种方式:
//    char buf[1024] = {0};
//    while(ifs >> buf){
//        cout << buf<<endl;
//    }

//第二种方式:
//    char buf[1024] = {0};
//    while(ifs.getline(buf,sizeof (buf))){
//        cout << buf<< endl;
//    }

//第三种
//    string buf;
//    while(getline(ifs,buf)){
//        cout << buf<<endl;
//    }

//第四种:EOF 文件尾部的标志。
    char c;
    while((c=ifs.get())!= EOF){
        cout << c<<endl;
    }
    //5.关闭流。
    ifs.close();
}


int main() {
//    writeFile();
    readFile();
    return 0;
}



#include <fstream>

/**
 * 通过二进制的形式对文件进行读写。
 */
class Person145 {
public :
    char m_Name[64];
    int m_Age;
};

void writeF() {
    //1,包含头文件。
    //2,创建写文件流。
    ofstream ofs;
    //3.打开文件。
    ofs.open("person.txt", ios::out | ios::binary);
    //4.写内容。
    Person145 person145;
    strcpy(person145.m_Name, "张三");
    person145.m_Age = 18;
    ofs.write((const char *) &person145, sizeof(Person145));
    //5.关闭流
    ofs.close();
}

void readF() {
    //1,包含头文件。
    //2,创建写文件流。
    ifstream ifs;
    //3.打开文件。
    ifs.open("person.txt", ios::in | ios::binary);
    if (!ifs.is_open()){
        cout <<"打开文件失败。"<<endl;
        return;
    }
    //4.读内容。
    Person145 person145;
    ifs.read((char *)&person145,sizeof (person145));
    cout << person145.m_Name << "," << person145.m_Age<<endl;
    //5.关闭流
    ifs.close();
}

int main() {
//    writeF();
    readF();
    return 0;
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...