注册 登录
编程论坛 C++教室

有关链表问题:将文件中的数据读入到链表中在打印到屏幕上最后一行总出现乱码求高手!...

芦浩轩 发布于 2012-06-01 17:08, 664 次点击
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
struct advices
{
    char adv[100];
   

    advices *next;
};

advices *adread()
{
   
advices *p,*q,*head;


    FILE *fp;
    head=new advices;
    if(head==NULL)
    {
    cout<<"开辟失败!!"<<endl;
    exit(1);

    }

    q=head;
    if((fp=fopen("15.txt","rb"))==NULL)
    {
        cout<<"系统无信息请稍后建立!!!"<<endl;
        return head;
    }
    fread(q,sizeof(advices),1,fp);


    while(!feof(fp))
   
    {
        if((p=(advices *)malloc(sizeof(advices)))==NULL)
        {

            cout<<"读取失败!!"<<endl;
            exit(1);
        }

      
        fread(p,sizeof(advices),1,fp);
        q->next=p;
        q=p;
    }
   q->next=NULL;
    fclose(fp);
    return head;


}

int main()
{
FILE *fp;
    advices *p;
   

advices *head,*p1,*p2;
head=new advices;
p1=head;

for(int i=0; ;i++)
    {
    p2=new advices;
        
   
    cout<<"请在此写下你的留言以q退出\n====>>>>"<<endl;
    cin>>p2->adv;
   

    if((strcmp(p2->adv ,"q"))==0)
    {
        free(p2);
        break;
    }
     p1->next=p2;
    p1=p2;
    }
    p1->next=NULL;


    p=head;

if((fp=fopen("15.txt","wb"))==NULL)
   {
      cout<<"打开失败!!"<<endl;
      return 0;
   }
    while(p)
    {
        fwrite(p,sizeof(advices),1,fp);
        p=p->next;
   
    }
    cout<<"信息保存成功!!"<<endl;
    fclose(fp);
   
    head=adread();
    head=head->next;
    while(head)
    {
   
    cout<<head->adv<<endl;
    head=head->next;
    }
   
    return 0;
   



}
只有本站会员才能查看附件,请 登录

1 回复
#2
芦浩轩2012-06-03 16:59
假如每个adread结构体占8个字符
文件中有两个结构体 一个是头(head)另一个存的内容
也就是说文件结束符在第17个字符的位置
你while那里的判断是文件结束符
当读完第二个结构体时文件指针在第16个位置,该位置不是文件结束符(应该是第17个),所以你的程序会再读一个无意义数据  就是你乱码的由来。
第二个改动只是更加严谨,我猜不像我那么改也应该可以,我没有试。
1