C++中的文件写入和读取(文本文件方式,二进制方式)

一、文件的写入

1 // 写文件操作  文本文件写入
2 ofstream ofs;
3 ofs.open("temp.txt",ios::out);
4 ofs << "姓名:张三" << endl;
5 ofs << "性别:男" << endl;
6 ofs << "学校:楚雄师范学院" << endl;
7 ofs.close();
//写文件  二进制方式操作
class Person
{
public:
    char m_name[64];
    int m_age;
};
void main()
{
    ofstream ofs;
    ofs.open("Person.txt",ios::out | ios::binary);
    Person p = { "张三",18 };
    ofs.write((const char *)&p, sizeof(Person));
    ofs.close();

}

二、文件的读取(5中方式)

1~4  文本文件读取

5      二进制文件读取

方式1:

1     //1.
2     ifstream ifs;
3     ifs.open("temp.txt", ios::in);
4     char buf1[1024] = { 0 };
5     while (ifs >> buf1)
6     {
7         cout << buf1 << endl;
8     }
9     ifs.close();

方式2:

1       2. 
2     ifstream ifs;
3     ifs.open("temp.txt",ios::in);
4     char buf2[1024] = { 1 };
5     while (ifs.getline(buf2,sizeof(buf2)))
6     {
7         cout << buf2 << endl;
8     }
9     ifs.close();

方式3:

1     3.
2     ifstream ifs;
3     ifs.open("temp.txt",ios::in);
4     string str;
5     while (getline(ifs,str))
6     {
7         cout << str << endl;
8     }
9     ifs.close();

方式4(不推荐):

    //4.(不推荐)
    ifstream ifs;
    ifs.open("temp.txt",ios::in);
    if (! ifs.is_open())
    {
        return 0;
    }
    char ch;
    while (( ch = ifs.get())  != EOF)
    {
        cout << ch;
    }
    ifs.close();

 方式5:

    // 读文件   二进制方式
    ifstream ifs;
    ifs.open("Person.txt",ios::in | ios::binary);
    if (! ifs.is_open())
    {
        return 0;
    }
    Person p2;
    ifs.read((char *)&p2, sizeof(Person));
    ifs.close();
    cout << p2.m_name << endl;
    cout << p2.m_age << endl;
原文地址:https://www.cnblogs.com/spiderljx/p/13130809.html