【C++】读写文件

  • 简单的读写文件方法
  • 直接上代码
#include
#include    //文件操作必用头文件
using namespace std;


/*
文件类型:
1.文本文件:ASCLL
2.二进制文件: 顾名思义
*/

/*
1.ofstream:写
2.ifstream:读
3.fstream:读写
*/


/*
文本文件
写步骤:
1.包含头文件  #include
2.创建流对象  ofstream ofs;
3.打开文件  ofs.open("文件路径",打开方式);
4.写数据 ofs<<"写入数据";
5.关闭文件 ofs.close();

读步骤:
1.包含头文件  #include
2.创建流对象 ifstream ifs;
3.打开文件并判断文件是否打开成功  ifs.open("文件路径","打开方式");
4.读数据  三种方式读取即可
5.关闭文件 ifs.close();
*/

/*
文件打开方式:较常用
ios::in   为读文件而打开文件,而且文件必须已经存在
ios::out  为写文件而打开文件
ios::trun  若文件已经存在,则清空其内容在写入,若文件不存在,则创建该文件
ios::binary  以二进制的方式打开文件
ios::app 将数据添加至文件尾部,文件必须已经存在
*/

void test_write()  //文本文件写
{
     
    ofstream obj;
    cout<<"--------写文件--------"<<endl;
    obj.open("C:/Users/10369/Desktop/test.txt", ios::out);

    obj<<"秋山刀名鱼"<<endl;
    obj<<"求三连"<<endl;
    obj.close();

}

void test_read()   //文本文件读
{
     
    ifstream obj;
    cout<<"--------读文件--------"<<endl;
    obj.open("C:/Users/10369/Desktop/test.txt", ios::in);
    if( !obj.is_open() )
    {
     
        cout<<"文件打开失败!"<<endl;
        return;
    }
    else
    {
     
        //第一种
        /*
        char buf[1024] = { 0 };
        while( obj>>buf )
        {
            cout<
       //第二种
       /*
        char buf[1024] = { 0 };
        while( obj.getline( buf, sizeof(buf)) )
        {
            cout<
       //第三种
       string buf;
        while( getline(obj, buf))
        {
     
            cout<<buf<<endl;
        }
        obj.close();
    }
    
}

class person{
     
    public:
        int _num;
};

void test_bin_write()   //二进制文件写
{
     
    ofstream obj;
    obj.open("C:/Users/10369/Desktop/test_bin.txt", ios::out | ios::binary);
    person temp = {
     345352};
    //ostream& write(const char *p, int len);
    obj.write((const char *)&temp, sizeof(person));
    obj.close();
}


void test_bin_read()  //二进制文件读
{
     
    ifstream obj;
    obj.open("C:/Users/10369/Desktop/test_bin.txt", ios::in | ios::binary);
    if( !obj.is_open() )
    {
     
        cout<<"文件打开失败!"<<endl;
    }
    else
    {
     
        person temp;
        obj.read((char*)&temp, sizeof(person));
        cout<<"读取数值:"<<temp._num<<endl;
        obj.close();
    }
    
}

int main()
{
     
    test_write();
    test_read();
    test_bin_write();
    test_bin_read();
}

你可能感兴趣的:(C++,c++,读写文件)