/* C Programming, Project 9 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
struct record {
char name[20];
char sex;
double score;
};
int queryDB(char [], struct record *);
void insertDB(struct record *);
void listAllName(void);
char *getLine(FILE *);
int main(void)
{
struct record *stdPtr;
char qname[20];
char ch;
int idx, ifFound;
do {
printf("Command(h for help):");
ch = getche();
switch (ch) {
case 'h':
printf("\nUse\n");
printf("h to show this help;\n");
printf("f to find a record by name;\n");
printf("l to list all names in the file;\n");
printf("i to insert a new record;\n");
printf("d to delete a specified record;\n");
printf("m to modify a specified record;\n");
printf("q to quit.\n");
break;
case 'f':
printf("\nFind the name:");
gets(qname);
ifFound = queryDB(qname, stdPtr);
if (!ifFound) {
printf("\nName %s not found!\n", qname);
} else {
printf("\nName: %s\n", stdPtr->name);
printf("Sex: %c\n", stdPtr->sex);
printf("Score: %f\n", stdPtr->score);
}
break;
case 'l':
listAllName();
break;
case 'i':
break;
case 'd':
break;
case 'm':
break;
case 0xd:
break;
case 'q':
printf("\nQuit now.\n");
break;
default:
printf("\nNot a valid command\n");
}
fflush(stdin);
printf("\n");
} while (ch!='q');
system("pause");
return 0;
}
int queryDB(char qname[], struct record *stdPtr) {
struct record *studtemp;
char *str, aname[20];
char asex;
double ascore;
FILE *fptr;
int i, rno, found=0;
fptr = fopen("db.txt","r");
if (fptr==NULL)
return 0;
else {
fscanf(fptr, "%d\n", &rno);
for (i=0;i<rno;i++) {
str = getLine(fptr);
strcpy(aname, str);
str = getLine(fptr);
asex = str[0];
str = getLine(fptr);
ascore = atof(str);
if (!strcmp(aname,qname)) {
strcpy(stdPtr->name, aname);
stdPtr->sex = asex;
stdPtr->score = ascore;
found = 1;
}
}
fclose(fptr);
if (found)
return 1;
else
return 0;
}
}
void insertDB(struct record *stdPtr) {
}
void listAllName(void) {
FILE *fptr;
int i, rno=0;
char *str;
fptr = fopen("db.txt","r");
if (fptr==NULL)
printf("Failed to open file\n");
else {
fscanf(fptr, "%d\n", &rno);
printf("\n");
for (i=0;i<rno;i++) {
str = getLine(fptr);
puts(str);
str = getLine(fptr);
str = getLine(fptr);
}
}
fclose(fptr);
}
char *getLine(FILE *fptr) {
static char str[80];
int i=0;
while ((str[i]=getc(fptr)) != '\n')
i++;
str[i] = '\0';
return str;
}
作業九題目
回到首頁
沒有留言:
張貼留言