《C Primer PLus》第五版上的例子,亲自输入了一下。 功能就是读取一个文件的内容,然后统计字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INSERT 1
#define QUERY 2
#define UPDATE 3
#define DELETE 4
#define LIST 5
#define QUIT 0
FILE *fp;
typedef struct
{
char name[100]; //students' name
char addr[100]; //students' address
char phone[100]; //students' telephone
char workfor[100]; //work unit
} TX;
TX txl[100]; // An array of alumni record, Up to one hundred students
int last = 0; //The current number of alumni
void show_menu();
void do_choice(int);
int get_choice();
void do_quit();
void do_insert();
void do_update();
void do_query();
void do_delete();
void do_list_all();
void init();
int main(int argc, const char *argv[])
{
int choice;
init();
while (1)
{
//1.display the main menu
show_menu();
//2.retrieve the user opition
choice = get_choice();
//3.According to the function of the corresponding choice of implementation
do_choice(choice);
//Sleep 5 sec, let the user see clearly
sleep(3);
// system("pause>nul");
}
return 0;
}
/* Increase initial classmates information*/
void init()
{
int i = 0;
if ((fp = fopen("tx1.txt", "rb")) == NULL)
{
//printf("can't open alumni information tx1.txt, please check on !\n");
//exit(0);
last = 0;
}
else
{
while (!feof(fp))
{
if (fread(&txl[i], sizeof(TX), 1, fp) == 1)
{
//printf("read the first %d student\n", i);
//sleep(5);
i++;
}
}
last = i;
}
fclose(fp);
}
void save()
{
int i = 0;
if ((fp = fopen("tx1.txt