C语言单向链表中如何往文件里存入数据和读取数据?
花了我半个小时,给了写了一个简单的例子,以下是在vs2005下调试成功,test.txt为文件名,在当前目录下。
#include
#include
#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;
}