C语言怎么从文件中将信息导入链表中

C语言怎么从文件中将信息导入链表中,第1张

这个实现起来挺简单的,就是写起来麻烦点,不是一点代码能写完的!

1,建立一个链表,链表的节点struct定义为联系人信息的格式;

2,读取文件,把内容存入链表;

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

}

只需要将文件标示为二进制即可。\x0d\x0astruct student stu[256]\x0d\x0a//将stu赋值...\x0d\x0a\x0d\x0aFILE * fd=fopen("c:\\test.bin","wb")//打开\x0d\x0aint i\x0d\x0afor(i=0i 回答于 2022-11-16


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11640313.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存