读写文件
class Perso
{
public:
char m_Name[64];
int m_Age;
};
/*
ios::in read file;
ios::out write file;
ios::ate 文件尾部
ios::app 追加写入文件
ios::trunc 如果文件已存在则删除后创建
ios::binary 二进制方式
ios::binary | ios ::out 二进制写
头文件:
ifstream 读
ofstream 写
fstream 读写
<< 左移运算符输出数据 到文件
>> 右移运算符读入数据 到内存
记得关闭数据close();
*/
void test()
{
//写入
//ofstream ofs;
//ofs.open("D:\\Project\\CPP\\demo\\demo1\\a.txt", ios::out);
//ofs.open("b.txt", ios::out);
//ofs <<"aaaaaaaaaaaaaaaa"<<endl
//<<"bbbbbbbbbbbbbbbbb"<<endl;
//ofs.close();
}
void test02()
{
//读取
ifstream ifs;
ifs.open("b.txt", ios::in);
//判断文件是否打开成功
if(!ifs.is_open())
{
cout<<"open fail"<<endl;
}
/*
char buff[1024] = {0};
while (ifs >> buff)
{
cout<<buff<<endl;
}
//一行一行块读
while(ifs.getline(buff, sizeof(buff)))
{
cout<<buff;
}
*/
/*
字符串一行一行读
string buff;
while(getline(ifs,buff))
{
cout<<buff;
}
*/
//字符一个一个读
char c;
while((c = ifs.get()) != EOF) //EOF end of file
{
cout<<c;
}
ifs.close();
}
void test03()
{
ofstream ofs("person.txt", ios::out | ios::binary);
Perso p = {"zhangsan", 18};
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
void test04()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if(!ifs.is_open())
{
cout<<"open fail"<<endl;
}
Perso p;
ifs.read((char*)&p, sizeof(Perso));
cout<<p.m_Name<<p.m_Age<<endl;
ifs.close();
}
int main()
{
test04();
system("pause");
system("cls");
return 0;
}