70,011
社区成员




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_LEN 10
#define TEL_LEN 12
typedef struct Node
{
char n[NAME_LEN];
char t[TEL_LEN];
struct Node* next;
}Node, *Linklist;
void InitLinklist(Linklist* L)
{
*L = (Linklist)malloc(sizeof(Node));
(*L)->next = NULL;
}
void CreateLinklist(Linklist L)
{
Node *r, *s;
char in[10];
char it[12];
r = L;
printf("请输入顾客姓名,电话号码:\n");
scanf("%s",in);
scanf("%s",it);
while(in[0]!='0') {
s = (Linklist)malloc(sizeof(Node));
strncpy(s->n, in, NAME_LEN);
strncpy(s->t, it, TEL_LEN);
r->next = s;
r = s;
printf("请输入顾客姓名,电话号码:\n");
scanf("%s",in);
scanf("%s",it);
}
r->next = NULL;
}
int WriteLinklistToFile(const char* strFile, Linklist L)
{
FILE *fpFile;
Linklist head = L->next;
if(!(fpFile = fopen(strFile,"a"))) {
printf("Open file failed\n");
return 0;
}
while(head) {
fprintf(fpFile,"%s\t%s\n",head->n, head->t);
head = head->next;
}
fclose(fpFile);
return 1;
};
int ReadFromFile(const char* strFile)
{
FILE *fpFile;
if (!(fpFile = fopen(strFile,"r")))
{
printf("Open file failed\n");
return 0;
}
printf("The contents of File are:\n");
while (!feof(fpFile))
putchar(fgetc(fpFile));
fclose(fpFile);
return 1;
}
void Destroy(Linklist L)
{
Linklist p = L, tmp;
while (p) {
tmp = p->next;
free(p);
p = tmp;
}
}
int main()
{
char* strName = "曾经顾客信息.txt";
Linklist L;
InitLinklist(&L);
CreateLinklist(L);
WriteLinklistToFile(strName, L);
ReadFromFile(strName);
Destroy(L);
return 0;
}
//s->n[0] = in[0]; //指向了临时变量,退出后会被销毁,你n的指向将会的内容是不可预测的
//s->t[0] = it[0];
strcpy(s->n, in); //char* 请使用strcpy函数进行深拷贝
strcpy(s->t, it);