提出一个简单的例子:
SAMPLE.TXT:
Bob 12
Joe 15
query.c:
#include <stdio.h>
struct record
{
char name[80];
int age;
};
int main(int argc, char *argv[])
{
struct record records[100];
int index = 0;
FILE *file = fopen(argv[1], "r");
while (fscanf(file, "%s %d", records[index].name, &records[index].age) != EOF)
index++;
printf("%s is %d years old.\n", records[0].name, records[0].age);
printf("%s, however, is %d years old.\n", records[1].name, records[1].age);
printf("Together, they have existed for %d years.\n", records[0].age + records[1].age);
return 0;
}
执行:query SAMPLE.TXT
为了别把这个例子弄得太复杂,我故意忽视了一些重要的问题。name和records都有任意的长度限制。假使SAMPLE.TXT内的资料太长,query会崩溃。如果没有命令行参数,或者参数指的文件根本不存在,也会发生同样的结果。如果输入SAMPLE.TXT的资料不符合格式,这也是一个问题。错误校验让你安排。这个程序应该输出:
Bob is 12 years old.
Joe, however, is 15 years old.
Together, they have existed for 27 years.