android源代码学习 init_parse_config_file(init.c)

###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

转载于:https://my.oschina.net/Genus/blog/104899

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值