laocai30 2022-05-14 10:58 采纳率: 76.3%
浏览 34
已结题

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;

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

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2022-05-14 12:12
    关注

    修改处见注释,供参考:

    #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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月30日
  • 已采纳回答 5月22日
  • 创建了问题 5月14日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分