uniq.c这个文件其实没读懂,不过从程序中发现了几个支点,下次再细细品。
第一。交换两行的写法。
#define SWAP_LINES(A, B) \
do \
{ \
struct linebuffer *_tmp; \
_tmp = (A); \
(A) = (B); \
(B) = _tmp; \
} \
while (0)
作者定义一个宏,而且而写一个只执行一次的循环,奇怪吧。我看到时,也算服了。你完全可以写成一个块语句呀,加上do while循环,岂不是画蛇添足。
#define SWAP_LINES(A, B) \
\
{ \
struct linebuffer *_tmp; \
_tmp = (A); \
(A) = (B); \
(B) = _tmp; \
} \
写成这样,难道不行吗?真是!
第二、字串数组
static char const *const delimit_method_string[] =
{
"none", "prepend", "separate", 0
};
作者用末尾的0表示字串结束了,这种技巧也很有用。
第三、用于比较的那段
while (!feof (istream))
{
char *thisfield;
size_t thislen;
if (readline (thisline, istream) == 0)
break;
thisfield = find_field (thisline);
thislen = thisline->length - 1 - (thisfield - thisline->buffer);
if (prevline->length == 0
|| different (thisfield, prevfield, thislen, prevlen))
{
fwrite (thisline->buffer, sizeof (char),
thisline->length, ostream);
SWAP_LINES (prevline, thisline);
prevfield = thisfield;
prevlen = thislen;
}
}
我的理解是,作者先定义两个串,prev表示前面一串,this表示当前串,当前串和前一串不等时,就要打印结构,并对prev前一串相关值进行更新。大体是这样。