//#include <iostream>
//using namespace std;
//#include <fstream>//头文件(读或写)
//#include <string.h>
//
写文件
//void test01() {
// ofstream ofs;//创建流对象
// ofs.open("test.txt", ios::out);//指定打开方式。ios::out是只写进入,ios::in是只读
// ofs << "姓名:张三" << endl;
// ofs << "职业:学生" << endl;
// ofs << "姓名:张宇超" << endl;
// ofs.close();
//}
//
读文件
//void test02() {
// ifstream ifs;
// ifs.open("test.txt", ios::in);
// if (!ifs.is_open()) {//bool类型看能不能打开
// cout << "文件打开失败" << endl;
// return;
// }
// //读文件
// char buf[1024] = { 0 };
// while (ifs >> buf) {//ifs读取,储存到buf中
// cout << buf << endl;
// }
//
// // string buf;
// //while (getline(ifs,buf)) {
// //cout << buf << endl;
// //}
// ifs.close();
// }
// int main() {
// test01();
// test02();
//
// }
//二进制文件读与写
#include <iostream>
using namespace std;
#include <fstream>//头文件(读或写)
#include <string.h>
class person {
public:
char m_name[64];
int m_age;
};
person p = { "张三",18 };
void test01(){
//包含头文件,
//创建流对象,
ofstream ofs;
// 打开文件,
ofs.open("person.txt", ios::out| ios::binary);
// 写文件
ofs.write((const char*)&p, sizeof(person));//穿地址
//关闭文件
ofs.close();
}
//读文件
void test02() {
ifstream ifs;
ifs.open("person.txt", ios::in |ios:: binary);
if (!ifs.is_open()) {//bool类型看能不能打开
cout << "文件打开失败" << endl;
return;
}
ifs.read((char*)&p, sizeof(person));
cout << "姓名是" << p.m_name << "年龄是" << p.m_age << endl;
ifs.close();
}
int main() {
test01();
test02();
}