#include
ofstream ofs;
ofs.open("文件路径",打开方式);
ofs<<"写入的数据";
ofs.close();
#include
ifstream ifs;
ifs.open("文件路径",打开方式);
//读取数据
char buf[1024] = {0};
while(ifs >> buf){
cout<< buf << endl;
}
ifs.close();
//方式一
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;
}
//方式四 不推荐
char c;
while( (c=ifs.get()) != EOF ){
cout<< c;
}
写文件
ofstream ofs;
ofs.open("person.txt",ios::out | ios::binary);
Person p = {"张三",18};
ofs.write((const char*)&p,sizeof(Person));
ofs.close();
读文件
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "文件打开失败";
return;
}
Person p;
ifs.read((char *) & p,sizeof(Person));
cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;