从文件中读入已写入的链表到新的链表中#includeiostream#includestringusing namespace stdstatic in
从文件中读入已写入的链表到新的链表中
#include<iostream>
#include<string>
using namespace std;
static int k=1;
class stu
{
protected:
int n;
char name[50];
public:
void setn(int);
void setname(char *);
int getn();
char* getname();
stu *next;
};
void stu::setn(int num){n=num;}
void stu::setname(char* Name){*name=*Name;}
int stu::getn(){return n;}
char* stu::getname(){return name;}
stu* creat()
{
stu *p1,*p2,*head;
p1=p2=new stu;
head=NULL;
int num;
char Name[50];
cin>>num>>Name;
p1->setn(num);
p1->setname(Name);
char m=' ';
while(m!='#')
{
if(k==1)
head=p1;
else
{
p2->next=p1;
p2=p1;
}
p1=new stu;
cin>>num>>Name;
p1->setn(num);
p1->setname(Name);
k++;
m=getchar();
}
p2->next=NULL;
return head;
}
void put_into_file(stu *p)
{
FILE *fp;
fp=fopen("C:\\Users\\Seffrui_M\\Desktop\\stu.txt","w");
if(fp==NULL)
{
cout<<"打开文件失败"<<endl;
exit(0);
}
do
{
fwrite(p,sizeof(stu),1,fp);/*向文件中写入class stu的时候 是只写数据 还是数据和函数一起写入文件 */
if(p->next==NULL)
break;
p=p->next;
}while(1);
}
void display(stu* p)
{
do
{
cout<<p->getn()<<endl;
cout<<p->getname()<<endl;
if(p->next==NULL)
break;
p=p->next;
}while(1);
}
void put_outof_file()/*这个函数是问题 我想写一个函数 来实现从stu.txt中的链表读入到新的链表p中 怎么实现*/
{
stu* p;
p=nullptr;
FILE *fp=fopen("C:\\Users\\Seffrui_M\\Desktop\\stu.txt","r");
fread(p,sizeof(stu),k,fp);
display(p);
}
int main()
{
stu* head;
head=creat();
put_into_file(head);
put_outof_file();
system("Pause");
return 0;
}
还有 我向文件中写入class的时候
[解决办法]
stu* p;//这里的p需要先申请空间
p=nullptr;
FILE *fp=fopen("C:\\Users\\Seffrui_M\\Desktop\\stu.txt","r");
fread(p,sizeof(stu),k,fp);
可以写成这样:
stu p;
FILE *fp=fopen("C:\\Users\\Seffrui_M\\Desktop\\stu.txt","r");
while(fread(&p,sizeof(stu),k,fp) !=0)
{
display(p);
};
[解决办法]
while(fread(&p,sizeof(stu),1,fp) !=0)
{
display(p);
};
fclose(fp); //楼主的代码都没有调用过fclose,汗一个
[解决办法]
为什么要有数据结构这个东东?
因为要将现实世界或者抽象理论中的各种数据保存在计算机外存(光盘、硬盘、U盘……)或内存(ROM、RAM、SRAM……)里面的二进制字节数组中。
然后让CPU这个只会执行预先保存好的加减乘除移位条件转移……等机器指令的家伙按照人的意志去处理这些数据。至于具体如何处理就是所谓算法。
推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
