厚德博学 敬业乐群
@sky
全部博文(252)
2015年(2)
2014年(1)
2013年(1)
2012年(16)
2011年(42)
2010年(67)
2009年(87)
2008年(36)
25742040
shijiulo
niuxlinu
ebayboy
hayand66
大鬼不动
acer1025
醉鬼的故
小雅贝贝
XINGCHEN
wzy_yzw
十的9次
zds05
bjywxc
zlhc1
smile124
cynthia
格伯纳
分类: LINUX
2008-04-02 21:45:03
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define BUFFSIZE 4096 #define ALIGN (sizeof(unsigned long) - 1) struct list_head { struct data_item *prev; struct data_item *next; }; struct data_item { struct data_item *prev; struct data_item *next; unsigned int dlen; char data[0]; }; static struct list_head head = { .prev = (struct data_item *) &head, .next = (struct data_item *) &head, }; static void item_enqueue_tail(struct list_head *head, struct data_item *item) { struct data_item *prev, *next; next = (struct data_item *) head; prev = next->prev; item->prev = prev; item->next = next; next->prev = prev->next = item; } static struct data_item * item_dequeue_head(struct list_head *head) { struct data_item *prev, *next, *result = NULL; prev = (struct data_item *) head; next = prev->next; if (prev == next) goto out; result = next; next = next->next; prev->next = next; next->prev = prev; result->prev = result->next = NULL; out: return result; } static struct data_item * item_alloc(ssize_t dlen) { struct data_item *item = NULL; ssize_t len; len = (sizeof(struct data_item) + dlen + ALIGN) & ~ALIGN; item = (struct data_item *) malloc(len); if (item) { memset(item, '\0', len); item->dlen = dlen; } return item; } static void travel(struct list_head *head) { struct data_item *item = NULL; while ((item = item_dequeue_head(head)) != NULL) { write(STDOUT_FILENO, item->data, item->dlen); free(item); } } int main(void) { char buf[BUFFSIZE]; ssize_t len; struct data_item *item = NULL; for (;;) { memset(buf, '\0', sizeof(buf)); len = read(STDIN_FILENO, buf, sizeof(buf)); if (len <= 0) break; item = item_alloc(len); if (item) item_enqueue_tail(&head, item); } travel(&head); return 0; }
上一篇:双向循环链表
下一篇:一个用预先分配的缓冲区读取输入程序(保留工作会用到)
登录 注册