c语言中怎么根据文件建立一个链表

Python029

c语言中怎么根据文件建立一个链表,第1张

依次是编号

名字

数据是么?你需要先建立一个creat.txt文件,然后对文件进行操作~!

头文件用#include<stdio.h>

#include<stdlib.h>这两个,然后定义个文件指针

FILE

*fp

用fopen("creat.txt","r")进行写入,写入用fscanf(fp,"%f%s%f",&id,&name,&grade)操作完成关闭文件fclose(fp)这样就行了~!在链表里插入这些东西就可以进行写入了。。具体还是靠自己写,要考试了,具体程序没有时间给你写。。

#include <stdio.h>

#include <stdlib.h>

#define TRUE 1

#define FALSE 0

typedef struct Node

{

int num

int score

struct Node* next

}Node, *Linklist

void InitLinklist(Linklist* L) //初始化单链表,建立空的带头结点的链表

{

*L = (Node*)malloc(sizeof(Node))

(*L)->next = NULL

}

void CreateLinklist(Linklist L) //尾插法建立单链表

{

Node *r, *s

r = L

int iNum, iScore

printf("Please input the number and score:\n")

scanf("%d",&iNum)

scanf("%d",&iScore)

while(0 != iScore) //当成绩为负时,结束输入

{

s = (Node*)malloc(sizeof(Node))

s->num = iNum

s->score = iScore

r->next = s

r =s

printf("Please input the number and score:\n")

scanf("%d",&iNum)

scanf("%d",&iScore)

}

r->next = NULL//将最后一个节点的指针域置为空

}

int WriteLinklistToFile(const char* strFile, Linklist L)

{

FILE *fpFile

Node *head = L->next

if(NULL == (fpFile = fopen(strFile,"w"))) //以写的方式打开

{

printf("Open file failed\n")

return FALSE

}

while(NULL != head)

{

fprintf(fpFile,"%d\t%d\n",head->num,head->score)

head = head->next

}

if(NULL != fpFile)

fclose(fpFile)

return TRUE

}

int ReadFromFile(const char* strFile)

{

FILE *fpFile

if(NULL == (fpFile = fopen(strFile,"r"))) //以读的方式打开

{

printf("Open file failed\n")

return FALSE

}

printf("The contents of File are:\n")

while(!feof(fpFile))

putchar(fgetc(fpFile))//证明fprintf()输出到文件中的绝对是字符串

if(NULL != fpFile)

fclose(fpFile)

return TRUE

}

void Destroy(Linklist L)

{

Node *head =L

while (head)

{

Node* temp = head

head = head->next

free(temp)

}

}

int main()

{

char* strName = "test.txt"

Linklist L

InitLinklist(&L)

CreateLinklist(L)

WriteLinklistToFile(strName, L)

ReadFromFile(strName)

Destroy(L)

return 0

}