|
ちょっと長くなってしまいましたが。
#include <stdio.h>
typedef struct node_ {
int key;
char name[BUFSIZ];
struct node_ *next;
} node_t;
node_t head;
void
insert(int key, const char *name)
{
node_t *pnext = head.next, *pprev = &head;
while (NULL != pnext && (key > pnext->key)) {
pprev = pnext;
pnext = pnext->next;
}
{
node_t *p = (node_t *)malloc(sizeof(node_t));
if (NULL == p) {
fprintf(stderr, "malloc err.\n");
return;
}
p->key = key;
snprintf(p->name, sizeof(p->name), name);
p->next = pnext;
pprev->next = p;
}
}
int
main(int argc, char *argv[])
{
char buf[BUFSIZ];
FILE *fpr = NULL;
head.next = NULL;
if (2 != argc) {
fprintf(stderr, "cmd arg err.\n");
return 1;
}
fpr = fopen(argv[1], "r");
if (NULL == fpr) {
fprintf(stderr, "fopen err.\n");
return 1;
}
while (NULL != fgets(buf, sizeof(buf), fpr)) {
int tmpKey;
char tmpName[BUFSIZ];
if (2 != sscanf(buf, "%d%s", &tmpKey, tmpName)) continue;
insert(tmpKey, tmpName);
}
{
node_t *ptr;
for (ptr = head.next; ptr != NULL; ptr = ptr->next) {
printf("%-8d %s\n", ptr->key, ptr->name);
free(ptr);
}
}
fclose(fpr);
return 0;
}
|