为什么要进行文件操作:
程序运行时产生的数据属于临时数据,程序一旦运行结束后都会被释放。通过文件可以将数据持久化,操作文件需要include <fstream>。
操作文件的三大类:ofstream(写操作) ifstream(读操作) fstream(读写操作)
示例1,读写文本文件:
#include <iostream>
#include <string>
#include <fstream> // 包含头文件 fstream
using namespace std;
// 写文件
void test01() {
// 创建流对象
ofstream ofs;
// 指定打开方式
ofs.open("test.txt", ios::out);
// 写内容
ofs << "姓名:张三" << endl;
ofs << "姓别:男" << endl;
ofs << "年龄:18" << endl;
}
// 读文件
void test02() {
// 创建流对象
ifstream ifs;
// 打开文件并判断是否成功
ifs.open("test.txt", ios::in);
// 读内容
if (!ifs.is_open()) {
cout << "open file fail" << endl;
return;
}
//方法一
/*char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}*/
//方法二
/*char buf[1024] = {};
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
}*/
//方法三
string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
}
//方法四
/*char c;
while ((c=ifs.get()) != EOF) {
cout << c;
}*/
}
int main() {
//test01();
test02();
return 0;
}
示例2,读写二进制文件:
#include <iostream>
#include <string>
#include <fstream> // 包含头文件 fstream
using namespace std;
class person {
public:
char m_name[64];
int m_age;
};
void test01() {
ofstream ofs;
// 打开文件
ofs.open("person.txt", ios::out | ios::binary);
// 写文件
person p = { "张三", 18 };
ofs.write((const char*)&p, sizeof(person));
}
void test02() {
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "fail to open" << endl;
return;
}
person p;
ifs.read((char*)&p, sizeof(person));
cout << "姓名:" << p.m_name << " 年龄: " << p.m_age << endl;
ifs.close();
}
int main() {
test01();
test02();
return 0;
}
感觉这里黑马讲的太糙了,实际运用的时候需要再查更细节的操作。