#include<stdio.h>
#include<string.h>
struct Person
{
char name[100];
int age;
int sex;
char add[100];
};
int main(int argc, char* argv[])
{
FILE *FIN;
char STRING_COMMAND[30];
if((FIN=fopen("c:/abc.txt","a+"))==NULL)
{
printf("不能打开该文件,或者找不到该文件~");
return 0;
}
else
{
printf("请使用以下命令来完成操作:\n");
}
printf("-lsall list all the person`s info! \n");
printf("-insert insert one person`s info \n");
printf("-exit exit the progronam \n");
printf("-lsname list all the person`s name \n");
printf("-lsnameinfo[name] display the info of one person \n");
while(1)
{
gets(STRING_COMMAND);
if(strcmp(STRING_COMMAND,"-lsall")==0)
{ fseek(FIN,0,SEEK_SET);
char in;
in=getc(FIN);
while(in!=EOF)
{
printf("%c",in);
in=getc(FIN);
}
printf("Query successfully!\n");
continue;
}
else if(strcmp(STRING_COMMAND,"-insert")==0)
{
struct Person newPerson;
printf("name:");
scanf("%s",&newPerson.name);
printf("age:");
scanf("%d",&newPerson.age);
printf("sex:");
scanf("%d",&newPerson.sex);
printf("address:");
scanf("%s",&newPerson.add);
fseek(FIN,0,SEEK_END);
fprintf(FIN,"name:%s\nage:%d\nsex:%d\naddress:%s\n",newPerson.name,newPerson.age,newPerson.sex,newPerson.add);
printf("Insert successfully!\n");
continue;
}
else if(strcmp(STRING_COMMAND,"-lsname")==0)
{
fseek(FIN,0,SEEK_SET);
struct Person QueryName;
while(feof(FIN)==0)
{
fscanf(FIN,"name:%s\n",&QueryName.name);
fscanf(FIN,"age:%d\n",&QueryName.age);
fscanf(FIN,"sex:%d\n",&QueryName.sex);
fscanf(FIN,"add:%s\n",&QueryName.add);
printf("%s\n",QueryName.name);
}
printf("Query successfully!");
}
else if(strcmp(STRING_COMMAND,"-lsnameinfo")==0)
{ char ForCmp[20];
gets(ForCmp);
fseek(FIN,0,SEEK_SET);
struct Person QueryName;
while(feof(FIN)==0)
{
fscanf(FIN,"name:%s\n",&QueryName.name);
fscanf(FIN,"age:%d\n",&QueryName.age);
fscanf(FIN,"sex:%d\n",&QueryName.sex);
fscanf(FIN,"add:%s\n",&QueryName.add);
if(strcmp(QueryName.name,ForCmp)==0)
{
printf("name:%s\n",QueryName.name);
printf("age:%d\n",QueryName.age);
printf("sex:%d\n",QueryName.sex);
printf("address:%s\n",QueryName.add);
}
}
printf("Query successfully!");
}
else if(strcmp(STRING_COMMAND,"-exit")==0||strcmp(STRING_COMMAND,"-end")==0)
{
break;
}
else
{
printf("Bad command!\n");
}
}
fclose(FIN);
return 0;
}
自己参考下吧