開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第6章(構造体)、6.6(テーブル参照)、演習6-6を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 6-6.
コード
sample.c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
int getword(char *, int);
void getdef(void);
ungets(char *);
int main(int argc, char *argv[])
{
char w[MAXWORD];
struct nlist *p;
while (getword(w, MAXWORD) != EOF) {
if (strcmp(w, "#") == 0) {
def();
} else if (!isalpha(w[0])) {
printf("%s", w);
} else if ((p = lookup(w)) == NULL) {
printf("%s", w);
} else {
ungets(p->defn);
}
}
return 0;
}
void skipblank(void);
int getch(void);
struct nlist *install(char *, char *);
void undef(char *);
void def(char *s)
{
int c, i;
char def[MAXWORD], word[MAXWORD], name[MAXWORD];
skipblank();
if (strcmp(word, "define") == 0) {
getword(name, MAXWORD);
skipblank();
for (i = 0; i < MAXWORD - 1; i++) {
if ((def[i] = getch()) == EOF || def[i] == '\n') {
break;
}
}
def[i] = '\0';
install(name, def);
} else if (strcmp(word, "undef") == 0) {
skipblank();
undef(name);
}
}
#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE];
void undef(char *s)
{
int h;
struct nlist *pre, *np;
unsigned hash(char *);
pre = NULL;
h = hash(s);
for (np = hashtab[h]; np != NULL; np = np->next) {
if (strcmp(s, np->name) == 0) {
break;
}
pre = np;
}
if (np != NULL) {
if (pre == NULL) {
hashtab[h] = np->next;
} else {
pre->next = np->next;
}
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}
void skipblank()
{
int c;
while ((c = getch()) == ' ' || c == '\t')
;
ungetch(c);
}
だいたいこんな感じかなぁ〜
0 コメント:
コメントを投稿