c++ (文件读写操作)

文件读写操作「c++」

#include <fstream>
void test01()
{
      //ofstream ofs("./test.txt",ios::out | ios::trunc);
      //后期指定打开方式
      ofstream ofs;
      ofs.open("./test.txt",ios::out | ios::trunc);
      //判断是否打开成功
      if(!ofs.is_open())
      {   
          cout<<"打开失败"<<endl;
      }   
      ofs << "姓名: abc"<<endl;
      ofs << "姓名: 小赵"<<endl;
}
//读文件
void test02()
{
    ifstream ifs;
    ifs.open("./test.txt",ios::in);
    //判断是否打开成功
    if(!ifs.is_open())
    {   
        cout<<"打开失败"<<endl;
    }   
    //第一种方式
//    char buf[1024];
//    while(ifs>>buf)
//    {
//        cout<<buf<<endl;
//    }
    //第二种方式
//    char buf[1024];
//    while(!ifs.eof())
//    {
//        ifs.getline(buf,sizeof(buf));
//        cout<<buf<<endl; 
//    }                                                                                      
    //第三种方式
    char c;
    while((c =ifs.get()) != EOF)
    {   
        cout<<c;
    }   
}

posted on 2021-04-27 00:35  lodger47  阅读(100)  评论(0)    收藏  举报

导航