一、实现将信息插入链表并打印
(1)定义及说明
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
(2)将某文件夹下的所有文件部分相关信息插入内核list
// 主实现
struct list_head* get_file_list(const char *dir,struct list_head *head)
{
struct dirent **namelist; // struct dirent * namelist[];
struct file_t *node= (struct file_t *)calloc(1, sizeof (struct file_t));
if (!node){
return NULL;
}
INIT_LIST_HEAD(&node->list);
chdir(dir);
int count = scandir(dir, &namelist,sfilter, alphasort);
if (count < 0) {
perror("scandir error");
goto Exit;
}
int i = 0;
for (i = 0; i < count; i++){
memset(node, 0, sizeof(*node));
struct dirent *entry = namelist[i];
uint64_t timestamp=get_timestamp(namelist[i]->d_name);
node->timestamp = timestamp;
strcpy(node->total_path,dir);
list_add_tail(&node->list,head);//尾插法
}
free(namelist);
return head;
}
Exit:
free(); // 注意异常退出的释放
(3)遍历此链表
// 遍历实现
list_for_each_entry(node,plist,list){
printf("filelist:path = %s\n" ,node->total_path);
printf("filelist:time = %ld\n",node->timestamp);
}
二、如何遍历链表并安全删除数据
(1)【list_for_each_entry_safe】定义及说明
/* @ pos: 用作循环光标的类型*
* @ n: 另一种类型*用作临时存储
* @ head: 链表list的头节点
* @ member: struct中list_struct的名称 */
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
(2)代码应用示例
// struct结构请根据需求填写,此处只是随意举例
struct offset {
struct list_head list;
int off_set;
off_t pos;
};
struct task_stat {
struct list_head list;
pthread_t thid;
int sockfd;
int timeout;
int port;
struct list_head offsets; /* list of struct offset */
};
void free_stat(struct task_stat* stat)
{
struct offset *off, *off_tmp;
if (!stat)
return;
list_for_each_entry_safe(off, off_tmp, &stat->offsets, list){
list_del(&off->list);
free(off);
}
free(stat);
}