程序代码:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct struct_nv_pair {
char name[5];
int value;
struct struct_nv_pair * next;
} nv_pair;
typedef struct {
nv_pair * head;
nv_pair * last;
} p_list;
char init_p_list(p_list * pl) {
pl->last = pl->head = (nv_pair *) malloc(sizeof(nv_pair));
if (pl->head == NULL) {
return 1;
}
pl->head->next = NULL;
return 0;
}
void append_parameter(p_list * pl, nv_pair * p) {
if (p == NULL) {
return;
}
p->next = NULL;
pl->last->next = p;
pl->last = p;
}
char get_parameter(int * value, p_list pl, char * name) {
nv_pair * p;
for (p = pl.head->next; p && strcmp(p->name, name); p = p->next);
if (p) {
*value = p->value;
return 0;
} else {
return 1;
}
}
int main() {
p_list pl;
nv_pair * p = NULL;
FILE * fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Failed to open data file.");
return 1;
}
if (init_p_list(&pl)) {
printf("Failed to init the parameter list.");
return 1;
}
while(!feof(fp)) {
p = (nv_pair *) malloc(sizeof(nv_pair));
if (p == NULL) {
printf("Failed to allocate memory.");
return 1;
}
fscanf(fp, " %s %d", p->name, &p->value);
append_parameter(&pl, p);
}
p = NULL;
fclose(fp);
p = pl.head->next;
while(p) {
printf("%s = %d\n", p->name, p->value);
p = p->next;
}
int v = 0;
if (get_parameter(&v, pl, "A")) {
printf("Parameter A not found.");
return 1;
}
printf("A = %d\n", v);
if (get_parameter(&v, pl, "D")) {
printf("Parameter D not found.");
return 1;
}
return 0;
}
测试文件如下:
程序代码:
A
100
B
29
C
283