1,建立一个链表,链表的节点struct定义为联系人信息的格式;
3,查询就根据姓名关键字遍历链表就行了;
4,把内容存入文件;
首先建立链表,以及插入节点,查询链表函数写出来;
文件的读取和存入到不是很麻烦;
----------------------------下面是简单的实现,可以输入,存入文件,从文件读取,打印,如果还想要实现其他的稍修改一下就行了------
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 80
struct stu{
int id
char name[MAX]
struct stu* next
}
typedef struct stu STU
typedef STU* STUPTR
STUPTR insert(STUPTR head, int id, char* name)
void print_st(STUPTR head)
void save_to_file(FILE* fp, STUPTR head)
FILE* crt_file( void )
STUPTR read_to_link(STUPTR head)
int main( void )
{
int choice
int stu_id
char stu_name[MAX]
STUPTR head
FILE* fp
clrscr()
head = NULL
clrscr()
printf( "please enter the choice!\n" )
scanf( "%d", &choice )
while( choice != 9 ){
switch(choice){
case 1: printf("enter the insert ----id---name!\n")
scanf( "%d%s", &stu_id ,stu_name)
head = insert(head,stu_id,stu_name)
break
case 2:print_st(head)
break
case 3:puts("save the info to file e:\stu_info.txt!\n")
fp = crt_file()
save_to_file( fp, head)
puts( "save the data sucessful!\n")
fclose(fp)
break
case 4:puts("read the file to link!\n")
head = NULL
head = read_to_link(head)
puts("read the file successful!\n")
break
}
printf( "please enter the choice!\n")
scanf( "%d", &choice )
}
}
STUPTR insert(STUPTR head, int id, char* name)
{
STUPTR new, cur
cur = head
new = malloc( sizeof( STU) )
new->id = id
strcpy(new->name, name)
new->next = NULL
if(cur == NULL)
head = new
else{
while(cur->next != NULL){
cur = cur->next
}
cur->next = new
}
return head
}
void print_st(STUPTR head)
{
STUPTR cur=head
int i
i=1
if(cur == NULL){
printf( "has no student info!\n" )
}
else while(cur != NULL){
printf( "%d:------%d---%s\n", i,cur->id,cur->name)
i++
cur = cur->next
}
}
void save_to_file(FILE* fp, STUPTR head)
{
int i
STUPTR cur
cur = head
while(cur != NULL){
fprintf(fp, "%d %s\n", cur->id,cur->name)
cur = cur->next
}
}
FILE* crt_file(void)
{
FILE* fp
fp = fopen( "e:\stu_info.txt", "w" ) /*w is right or not*/
if(fp == NULL)
puts("shit!!!!!!!!!!")
return fp
}
STUPTR read_to_link( STUPTR head)
{
int id
char name[MAX]
FILE* fp
fp = fopen("e:\stu_info.txt", "r")
while( !feof(fp) ){
fscanf(fp, "%d%s", &id, name )
head = insert(head, id, name)
}
return head
}
是按id由小到大插入的,比如一开始链表中的id是1、4、6、9,给一个id为3的就把他插到1和4之间。其实链表这个东西最好单步运行一下,只要弄懂一个链表的问题以后所有的问题就都会了,都差不多
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)