c++的文件的读写和写入

img

img


#include
#include
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stu[3] = { "Li",1001,18,'f',"hi",1002,13,'f' ,"wu",1003,18,'m' };
ofstream outfile("text.txt", ios::binary);
if (!outfile)
{
cerr << "open error!" << endl;
abort();

}
for (int i = 0; i < 3; i++)
{
    outfile.write((char*)&stu[i], sizeof(stu[i]));
    outfile.close();
}

student stud[3];
ifstream infile("text.txt", ios::binary);
if (!infile)
{
    cerr << "open error!" << endl;
    abort();

}
for (int i = 0; i < 3; i++)
{
    infile.read((char*)&stud[i], sizeof(stu[i]));
    infile.close();
}
for (int i = 0; i < 3; i++)
{
    cout << "NO." << i + 1 << endl;
    cout << "name:" << stud[i].name << endl;
    cout << "num:" << stud[i].num << endl;
    cout << "age:" << stud[i].age << endl;
    cout << "sex:" << stud[i].sex << endl;

}
return 0;

}
为什么会成这样子呀快久久俺吧

修改处见注释,供参考:

#include <iostream>
#include <fstream>
using namespace std;
struct student
{
    char name[20];
    int  num;
    int  age;
    char sex;
};
int main()
{
    student stu[3] = { "Li",1001,18,'f',"hi",1002,13,'f',"wu",1003,18,'m' };
    ofstream outfile("text.txt", ios::binary);
    if (!outfile)
    {
        cerr << "open error!" << endl;
        abort();
    }
    for (int i = 0; i < 3; i++)
    {
        outfile.write((char*)&stu[i], sizeof(stu[i]));
        //outfile.close();  这里循环三次关闭文件
    }
    outfile.close(); //移动到这里

    student stud[3];
    ifstream infile("text.txt", ios::binary);
    if (!infile)
    {
        cerr << "open error!" << endl;
        abort();
    }
    for (int i = 0; i < 3; i++)
    {
        infile.read((char*)&stud[i], sizeof(stud[i])); //sizeof(stu[i]) 修改
        //infile.close();  这里循环三次关闭文件
    }
    infile.close(); //移动到这里

    for (int i = 0; i < 3; i++)
    {
        cout << "NO." << i + 1 << endl;
        cout << "name:"<< stud[i].name << endl;
        cout << "num:" << stud[i].num << endl;
        cout << "age:" << stud[i].age << endl;
        cout << "sex:" << stud[i].sex << endl;
    }
    return 0;
}