【问题标题】:Reading and Writing a class data to binary file in VC++在 VC++ 中读取和写入类数据到二进制文件
【发布时间】:2012-12-17 14:28:06
【问题描述】:
class Student 
{
public:
Student *prev;  
char S_Name[15];
char F_Name[15];
int Reg_Num;
char Section;
char MAoI[15];
float CGPA;
Student *next;
} 

我有上面的类,我想在退出程序时将数据写入链接列表的二进制文件,并在程序运行时再次读回并形成链接列表。 我已经尝试了几次,但都失败了!

输入数据的代码`Student * Add_Entry() { 学生 *temp=new Student();

char s_Name[15];
char f_Name[15];
int reg_Num;
char section;
char mAoI[15];
float cGPA;

cout <<"**********************Menu***************************\n ";
cout<<"\nEnter the Studets name \"";
cin>>s_Name;

cout<<"\nEnter Father`s name \"";
cin>>f_Name;

cout<<"\nEnter the Registration Number \"";
cin>>reg_Num;

cout<<"\nEnter the Section \"";
cin>>section;

cout<<"\nEnter the Major Area of Interest \"";
cin>>mAoI;

cout<<"\nEnter the Current CGPA \"";
cin>>cGPA;

strcpy_s(temp->S_Name,s_Name);
strcpy_s(temp->F_Name,f_Name);
temp->Reg_Num=reg_Num;
temp->Section=section;
strcpy_s(temp->MAoI,mAoI);
temp->CGPA=cGPA;
temp->next=NULL;
temp->prev=NULL;
return temp;

//temp=Create_node(s_Name,f_Name,reg_Num,section,mAoI,cGPA);    

}`

要从文件中读取,我使用 ` char *buffer;

    ifstream reader;
    reader.open("student.bin",ios::in | ios::binary);
    if(reader.is_open)
    {
        do
        {
            reader.read(buffer,ch);
            if(Header==NULL)
            {
                Header=(Student)*buffer;
                temporary=Header;
            }

            else
            {
                temporary->next=(Student)*buffer;
                temporary=temporary->next;
            }
        }while(buffer!=NULL);
    }

`

要写我使用`temporary=Header; //备份条目 流作家; writer.open("student.bin",ios::out | ios::binary);

                while(temporary!=NULL)
                {   
                    writer.write((char)* temporary,sizeof(temporary));
                    temporary=temporary->next;
                }

                writer.close();

`

【问题讨论】:

  • 你能把你最近尝试的代码贴出来吗?
  • 您能否编辑您的问题以显示您如何创建链接列表以及如何将其写入文件?
  • 和以前一样,请编辑您的问题以包含此信息。您能否详细解释一下代码是如何“失败”的?如果它崩溃,请尝试确定发生在哪条线上。如果代码运行但给出了令人惊讶的输出,请说明您看到的输出以及您的预期。
  • 加载时,您似乎没有为列表中的最后一项填写“下一个”指针,也没有填写任何“上一个”指针。 (谁知道你没有发布的代码中发生了什么)
  • 数据类型转换报错

标签: c++ visual-c++


【解决方案1】:

这一行:

Header=(Student)*buffer;

意思是:获取缓冲区,它可能是一个指向 char 的指针,并取消引用它,得到一个char。然后将char 转换为Student。编译器不知道如何将char 转换为Student

如果你这样做:

Header= *((Student *)buffer);

它将指针转换为正确类型的指针,然后取消引用它以给出一个可以复制的结构。

你到处都这样做。

此外,在阅读时,您不会为最后一项填写“next”指针,也不会为任何一项填写“prev”指针。尽管最后保存的项目中的“下一个”指针可能为零(假设它被正确保存),但上一个指针可以指向任何东西。最佳做法是正确初始化所有内容。

还有:

if(reader.is_open)

应该是:

if(reader.is_open())

【讨论】:

  • 我是否必须将单个条目写入文件并读回?
  • 您应该能够或多或少地完成您现在正在做的事情,但是您需要按照描述的方式修复错误(也许更多)。我注意到您已经接受了我的回答 - 如果您还有其他问题,您应该提出一个新问题。如果我没有真正回答您的问题,您应该使用更多信息更新您的问题。
  • 我已经修复了错误,但问题仍然存在
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
相关资源
最近更新 更多