文件
#include<iostream> using namespace std; #include<fstream> test01(){ ofstream ofs; ofs.open("test.txt",ios::out); ofs<<"姓名"<<endl; ofs<<"性别"<<endl; ofs.close(); } test02(){ ifstream ifs; ifs.open("test.txt",ios::in); string bug; while(getline(ifs,bug)){ cout<<bug<<endl; } ifs.close(); } int main(){ test01(); test02(); system("pause"); return 0; }
二进制文件
#include<iostream> using namespace std; #include<fstream> class Person{ public: char m_Name[64];// int m_Age; }; void test01(){ //1.包含头文件 //2.创建流对象 ofstream ofs; //3.打开文件 ofs.open("person.txt",ios::out| ios::binary); //4.写文件 Person p={"zhangsan",18}; ofs.write((const char *)&p,sizeof(Person)); //5.关闭文件 ofs.close(); } void test02(){ ifstream ifs("person.txt",ios::in | ios::binary); if(!ifs.is_open()){ cout<<"打开失败"<<endl; return ; } Person p; ifs.read((char *)&p,sizeof(Person)); cout<<"xingming:"<<p.m_Name<<"age:"<<p.m_Age<<endl; ifs.close(); } int main(){ test01(); test02(); system("pause"); return 0; }