不用链表,单是结构体写入文件后,是否可以进行修改删除
#include <stdio.h>#include <stdlib.h>
#include <string.h>
typedef struct Node
{
char num[20];
char name[20];
}STU;
void add();
void read(char *);
void delete();
void visit();
int main()
{
while(1)
{
printf("1 add\n");
printf("2 delete\n");
int i;
scanf("%d",&i);
switch(i)
{
case 1:
add();
break;
case 2:
{
visit();
delete();
printf("===========================\n");
visit();
break;
}
default:
break;
}
}
return 0;
}
void delete()
{
char p[128];
char num[128];
int i=0;
FILE *fp=fopen("stu.txt","r+");
if(fp == NULL)
{
printf("文件不存在!\n");
exit(1);
}
STU *stu2=(STU *)malloc(sizeof(STU));
printf("输入需要删除的num!\n");
scanf("%s",num);
rewind(fp);
while(1)
{
fseek(fp,i*sizeof(STU),SEEK_SET);
fread(stu2,sizeof(STU),1,fp);
if(strcmp(p,stu2->num)==0)
{
break;
}
if(strcmp(num,stu2->num)==0)
{
free(stu2);
strcpy(stu2->num,"");
strcpy(stu2->name,"");
break;
}
strcpy(p,stu2->num);
i++;
}
fclose(fp);
}
void add()
{
FILE *fp=fopen("stu.txt","a+");
STU *stul=(STU *)malloc(sizeof(STU));
printf("请输入编号:\n");
scanf("%s",stul->num);
printf("请输入姓名:\n");
scanf("%s",stul->name);
if(fgetc(fp) != EOF)
{
read(stul->num);
}
fwrite(stul,sizeof(STU),1,fp);
fclose(fp);
}
void read(char *num)
{
char p[128]="abcd";
int i=0;
FILE *fp = fopen("stu.txt","r");
STU *stu2=(STU *)malloc(sizeof(STU));
rewind(fp);
while(1)
{
fseek(fp,i*sizeof(STU),SEEK_SET);
fread(stu2,sizeof(STU),1,fp);
if(strcmp(p,stu2->num)==0)
{
break;
}
if(strcmp(num,stu2->num)==0)
{
printf("用户名已经存在!\n");
break;
}
strcpy(p,stu2->num);
i++;
}
fclose(fp);
}
void visit()
{
char p[128]="abcd";
int i=0;
FILE *fp=fopen("stu.txt","r");
STU *stu2=(STU *)malloc(sizeof(STU));
rewind(fp);
while(1)
{
fseek(fp,i*sizeof(STU),SEEK_SET);
fread(stu2,sizeof(STU),1,fp);
if(strcmp(p,stu2->num)==0)
{
break;
}
printf("第%d次:%s %s\n",i,stu2->num, stu2->name);
strcpy(p,stu2->num);
i++;
}
fclose(fp);
}
不用链表,单是结构体好像不能进行修改删除动作,上述代码只是实现了读和写,删除没有实现,各位大大可否帮忙,谢谢了!