C語(yǔ)言單向鏈表中如何往文件里存入數(shù)據(jù)和讀取數(shù)據(jù)?
花了我半個(gè)小時(shí),給了寫了一個(gè)簡(jiǎn)單的例子,以下是在vs2005下調(diào)試成功,test.txt為文件名,在當(dāng)前目錄下。
#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) //初始化單鏈表,建立空的帶頭結(jié)點(diǎn)的鏈表
{
*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) //當(dāng)成績(jī)?yōu)樨?fù)時(shí),結(jié)束輸入
{
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; //將最后一個(gè)節(jié)點(diǎn)的指針域置為空
}
int WriteLinklistToFILE(const char* strFile, Linklist L)
{
FILE *fpFile;
Node *head = L->next;
if(NULL == (fpFile = fopen(strFile,"w"))) //以寫的方式打開(kāi)
{
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"))) //以讀的方式打開(kāi)
{
printf("Open file failed\n");
return FALSE;
}
printf("The contents of File are:\n");
while(!feof(fpFile))
putchar(fgetc(fpFile));//證明fprintf()輸出到文件中的絕對(duì)是字符串
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;
}