文件操作
 
// 文件操作
// 程序运行时产生的数据都属于临时数据,程序结束后临时数据会被操作系统释放
// 通过文件操作可以将数据持久化
// c++ 中文件操作需要包含头文件 <fstream>
// 文件类型分为两种:
// 文本文件: 文件以文本的ASCII码形式存储在计算机中
// 二进制文件: 文件以二进制形式存储在计算机中,任何文本编辑器都不能查看
// 操作文件的三个类
// ofstream  写操作
// ifstream  读操作
// fstream   读写操作
 
1. 文本文件
 
1.1 写文件
 
写文件步骤:
1. 包含头文件
#include <fstream>
2. 创建流对象
ofstream ofs;
3. 打开文件
ofs.open("文件名", ios::out);
4. 写数据
ofs << "写入的数据" << endl;
5. 关闭文件
ofs.close()
 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void test01() {
    
    
    ofstream ofs;
    
    ofs.open("test.txt", ios::out | ios::app);
    
    ofs << "name: zhangsan 11" << endl;
    ofs << "sex: man" << endl;
    ofs << "age: 18" << endl;
    
    ofs.close();
}
int main(int argc, char const *argv[]) {
    test01();
    return 0;
}
 
12. 读文件
 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void test01() {
    
    
    ifstream ifs;
    
    ifs.open("test.txt", ios::in);
    
    if (!ifs.is_open()) {
        cout << "文件打开失败" << endl;
        return;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    char c = '\0';
    
    while((c = ifs.get()) != EOF) {
        cout << c;
    }
    
    ifs.close();
}
int main(int argc, char const *argv[]) {
    test01();
    return 0;
}
 
2 二进制文件
 
以二进制文件对文件进行读写操作
打开方式要指定为ios:binary
 
2.1 写文件
 
写文件
二进制方式写文件主要是利用流对象调用成员write()方法
函数原型:ostream& write(const char* s, int len);
s:指向要写入的字符串的指针
len:写入的字符串长度
 
#include <iostream>
#include <fstream>
using namespace std;
class Person {
public:
    char m_name[64]; 
    int m_age;       
};
void test01() {
    
    
    ofstream ofs("person.txt", ios::out | ios::binary);
    
    
    
    Person p = {"张三", 18};
    ofs.write((const char*)&p, sizeof(Person));
    
    ofs.close();
}
int main() {
    test01();
    return 0;
}
 
2.2 读文件
 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Person {
public:
    char m_name[64]; 
    int m_age;       
};
void test01() {
    
    ifstream ifs;
    
    ifs.open("person.txt", ios::in | ios::binary);
    if (!ifs.is_open()) {
        cout << "文件打开失败" << endl;
        return;
    }
    
    Person p;
    while (ifs.read((char*)&p, sizeof(Person))) {
        cout << "name:" << p.m_name << " age: " << p.m_age << endl;
    }
    
    ifs.close();
}
int main() {
    test01();
    return 0;
}