###read_file函数(system/core/util.c) void *read_file(const char *fn, unsigned *_sz) { char *data; int sz; int fd;
data = 0;
fd = open(fn, O_RDONLY);
if(fd < 0) return 0;
// (1) 使用lseek查看文件长度。
sz = lseek(fd, 0, SEEK_END);
if(sz < 0) goto oops;
if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
data = (char*) malloc(sz + 2);
if(data == 0) goto oops;
if(read(fd, data, sz) != sz) goto oops;
close(fd);
data[sz] = '\n';
data[sz+1] = 0;
if(_sz) *_sz = sz;
return data;
// (2) 使用goto语句集中处理异常情况。
oops:
close(fd);
if(data != 0) free(data);
return 0;
}
###数据结构listnode的实现和使用(system/core/include/cutils/list.{h,c}) //list.h #ifndef CUTILS_LIST_H #define CUTILS_LIST_H
#include <stddef.h>
struct listnode
{
struct listnode *next;
struct listnode *prev;
};
#define node_to_item(node, container, member) \
(container *) (((char*) (node)) - offsetof(container, member))
// (1) 使用.成员名的初始化方式初始化结构体
#define list_declare(name) \
struct listnode name = { \
.next = &name, \
.prev = &name, \
}
// (2)使用宏来处理常用操作
#define list_for_each(node, list) \
for (node = (list)->next; node != (list); node = node->next)
#define list_for_each_reverse(node, list) \
for (node = (list)->prev; node != (list); node = node->prev)
void list_init(struct listnode *list);
void list_add_tail(struct listnode *list, struct listnode *item);
void list_remove(struct listnode *item);
// (2)使用宏来处理常用操作
#define list_empty(list) ((list) == (list)->next)
#define list_head(list) ((list)->next)
#define list_tail(list) ((list)->prev)
#endif