C++数据链表在txt中储存与读取问题

来源:互联网 发布:java封装修饰符 编辑:程序博客网 时间:2024/05/22 18:23

// text_savedata.cpp : 定义控制台应用程序的入口点。
//

#include "StdAfx.h"
#include <string>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <fstream>
#include <conio.h>
# define LEN sizeof(struct news)
# define NULL 0

using namespace std;

struct news
{
 char type;
 //int number;
    char title [30];
 char content [300];
 struct news * next;
};


struct news * creat(struct news * head)
{
 int n;
 char TC; 
 struct news * p1, * p2;
 n = 0;
 p1 = p2 = (struct news *) malloc(LEN);
 cout<<endl<<"请输入该新闻的类型标号:";
      cin>>p1->type;
     cout<<endl<<"请输入该新闻的标题:";
     cin>>p1->title;
     cout<<endl<<"请输入该新闻的内容:";
     cin>>p1->content;
  cout<<endl<<"退出请输入T "<<endl; 
  cin>>TC;
 head = NULL;
 head = p1;
 while(TC != 'T')//最好按回车即退出
 {
  n = n+1;
  /*if(n == 1)
   head = p1;
    else */
  p2->next = p1;
  p2 = p1;
  p1 = (struct news *)malloc(LEN);
  cout<<"请输入该新闻的类型标号:";
      cin>>p1->type;
     cout<<"请输入该新闻的标题:";
     cin>>p1->title;
     cout<<"请输入该新闻的内容:";
     cin>>p1->content; 
  cout<<"退出请输入T "<<endl; 
  cin>>TC;
  //cout<<n;
    
 }
 p2->next = p1;     //将最后一个结构体连接到链表中
 p1->next = NULL;
 return (head);
}

void print (struct news * head)  //输出链表中的数据
{
 int a = 0;
 struct news * p;
 cout<<"依次输出链表中的数据:"<<endl;
 p = head;
 if(head != NULL)
  do
  { a++;//前边的编号
      cout<<a;
   cout<<"新闻类型:"<<p->type<<endl<<"新闻标题:"<<p->title<<endl<<"新闻内容:"<<p->content<<endl;
   p = p->next;
   
  }while(p != NULL);
}

void savedata(struct news * head)    //保存数据
{
 struct news head1;  
 fstream file("data.txt",ios::out); 

 if(head != NULL)
 {
  while(head)
  {
   file.write((char *) head,sizeof(head1));  //获取结构体长度的二进制码
   head = head->next;              //指针下移
  }
 }
 file.close();
 cout<<"保存成功!";
}
struct news *  readdata ()     //读取数据
{
 news * P = new news ,* Q = P ; 
 P->next =NULL;
 
 struct news news1;
 fstream file("data.txt",ios::in);
 while(1)
 {
  file.read((char *)& news1,sizeof(news1));  
  if(!file)break;
  else
  { 
   struct news * V = (struct news *) malloc(LEN);
   //cout<<news1.type<<endl;
   //cout<<news1.title<<endl;  //测试用的
   //cout<<news1.content<<endl;
   
   V->type = news1.type;
   strcpy(V->title,news1.title);     //复制文件
   strcpy(V->content,news1.content);     
   //cout<<V->type<<V->title<<V->content<<endl;   //测试用的
   //cout<<"********************************************";
    
   Q->next = V;   
   Q->next ->next = NULL;
   Q = Q->next;    
  }
 }
 file.close();
 return (P->next);   //返回指针如果返回P则有个指向Q的多余指针
}
int main ()
{
 struct news * head;
 head = NULL;
 head = creat(head);
 savedata(head);
 head = readdata ();
  print(head);
 getch();
 return 0;
}

 

原创粉丝点击