C++文件的读取和写入

1、C++对txt文件的读,ios::in

#include
#include
using namespace std;

int main()
{
    ifstream ifs;
    ifs.open("test.txt",ios::in);
    if(!ifs.is_open())
    {
        cout<<"打开文件失败!"<<endl;
    }
    char buff[1024] ={0};
    while(ifs>>buff)
    {
        cout<<buff<<endl;
    }
    return 0;
}

2、c++对txt文件的写文件,ios::out

#include
#include
using namespace std;
int main()
{
    ofstream ofs;
    ofs.open("test1.txt",ios::out);
    ofs<<"岗位:LISI"<<endl<<"年龄:19"<<endl<<"xingbie:男"<<endl;
    ofs.close();
    return 0;
}

3、c++对txt文件的写文件,追加到目前文件的最后,ios::app

#include
#include
using namespace std;
int main()
{
    ofstream ofs;
    ofs.open("test1.txt",ios::app);
    ofs<<"岗位:LISI"<<endl<<"年龄:19"<<endl<<"xingbie:男"<<endl;
    ofs.close();
    return 0;
}

4、c++读取二进制文件,ios::in|ios::binary

#include
using namespace std;
#include
class CStudent
{
    public:
        char name[100];
        int age;
};

int main()
{
    CStudent cs;
    ifstream infile("student.dat",ios::in|ios::binary);
    if(!infile)
        cout<<"error"<<endl;
    while(infile.read((char*)&cs,sizeof(cs)))
    {
        int readBytes=infile.gcount();
        cout<<cs.name<<cs.age<<endl;
    }
    infile.close();
    return 0;
}


5、c++写二进制文件,ios::out|ios::binary

#include
#include
using namespace std;

class CStudent
{
    public:
        char name[100];
        int age;
};

int main()
{
    CStudent cs;
    ofstream outfile("student.dat",ios::out|ios::binary);
    while(cin>>cs.name>>cs.age)
        outfile.write((char*)&cs,sizeof(cs));
    outfile.close();
    return 0;
}

你可能感兴趣的:(c++,开发语言)