#include "stdio.h"
#include "stdlib.h"
int no,other;
char name[20];
//查询
void find()
{
FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");
if(fp==NULL)
exit(1); //异常处理
while(1)
{
fscanf(fp,"%d %s %d",&no,name,&other);
if(fgetc(fp)==EOF)
break; //遇文件结束符
printf("%03d %s %d\n",no,name,other);
}
fclose(fp);
}
//添加
void add()
{
FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","a+"); //追加
printf("Input NO,Name,Other:\n");
scanf("%d %s %d",&no,name,&other);
fprintf(fp,"%03d %s %d\n",no,name,other);
fclose(fp);
}
//修改
void edit()
{
printf("请输入修改的学号:\n");
int e_temNo;
int e_no[20],e_other[20];
char e_name[20][20];
scanf("%d",&e_temNo);
int l=0;
FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");
if(fp==NULL)
exit(1); //异常处理
while(1)
{
fscanf(fp,"%d %s %d",&e_no[l],e_name[l],&e_other[l]);
if(fgetc(fp)==EOF)
break; //遇文件结束符
// printf("%03d %s %d\n",no,name,other);
l++;
}
fclose(fp);
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","w");
for(int i=0;i<l;i++)
{
if(e_temNo==e_no[i]) //学号匹配
{
printf("原信息为:%03d %s %d\n",e_no[i],e_name[i],e_other[i]);
printf("Input NO,Name,Other:\n");
scanf("%d %s %d",&e_no[i],e_name[i],&e_other[i]);
}
fprintf(fp,"%03d %s %d\n",e_no[i],e_name[i],e_other[i]); //原样写回
}
fclose(fp);
}
//删除
void del()
{
printf("请输入删除的学号:\n");
int e_temNo;
int e_no[20],e_other[20];
char e_name[20][20];
scanf("%d",&e_temNo);
int l=0;
FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");
if(fp==NULL)
exit(1); //异常处理
while(1)
{
fscanf(fp,"%d %s %d",&e_no[l],e_name[l],&e_other[l]);
if(fgetc(fp)==EOF)
break; //遇文件结束符
// printf("%03d %s %d\n",no,name,other);
l++;
}
fclose(fp);
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","w");
for(int i=0;i<l;i++)
{
if(e_temNo!=e_no[i]) //学号匹配
{
fprintf(fp,"%03d %s %d\n",e_no[i],e_name[i],e_other[i]); //原样写回
}
}
fclose(fp);
}
int main(int argc, char* argv[])
{
int v;
printf("1:查询 2:插入 3:修改 4:删除\n");
while(~scanf("%d",&v))
{
if(v==1)
{
find();
}
else if(v==2)
{
add();
}
else if(v==3)
{
edit();
}
else
{
del();
}
printf("1:查询 2:插入 3:修改 4:删除\n");
}
return 0;
}
date.txt 文件内容:
001 小额 111
002 小何 222
003 小样 333
参考文献:
http://zhidao.baidu.com/question/1830196103434926340.html
http://blog.chinaunix.net/uid-11600035-id-2866020.html