文件检索(C循环双链表实现)

本文介绍了一种方法,通过读取目录中的文件名,将其放入循环双链表中,并提供了查看前一个、后一个文件及退出的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**********************************************************************************
读取目录中的文件名,放到循环双链表中,按1查看前一个,
按2查看后一个,按3退出。
**********************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"unistd.h"
#include"sys/types.h"
#include"fcntl.h"
#include"dirent.h"

struct DuLNode
{
    char num[100];
    struct DuLNode *prior,*next;
};
struct DuLNode *head=NULL;
struct DuLNode *tmp=NULL;
cre_list() //初始化
{
    head = (struct DuLNode *)malloc(sizeof(struct DuLNode));
    head->prior = head;
    head->next = head;
}
add_DuLNode(char *num) //插入结点
{
    if(head->num == 0)
    {
		strcpy(head->num,num);
    }
	else
	{	
		struct DuLNode *ptr = (struct DuLNode *)malloc(sizeof(struct DuLNode));
		strcpy(ptr->num,num);
	    ptr->next=head->next;
        head->next=ptr;
	    ptr->prior=head;
	    ptr->next->prior=ptr;
	}
}
display_DuLNode() //遍历链表
{
    struct DuLNode *p = head;
    do
    {
        printf("%s\n",p->num);
        p = p->next;
    }while(p!=head);
}
display_next_DuLNode() //
{
   // struct DuLNode *p = head;
	tmp= tmp->next;
    printf("%s\n",tmp->num);
}
display_prior_DuLNode() //
{
    //struct DuLNode *p = head;
	tmp= tmp->prior;
    printf("%s\n",tmp->num);
}

int main(int argc, char * argv[])
{
    int i=0;
    cre_list();
	DIR *dp;
	struct dirent *dirp;
	if (argc != 2) 
	{
		printf("Usage: ls directory_name");
	}	
	//打开指定的目录
	if ((dp = opendir(argv[1])) == NULL)
	{
		printf("can't open %s\n", argv[1]);
		exit(1);
	}	
	//遍历目录
	while ((dirp = readdir(dp)) != NULL)
	{
	    if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
	    {			
	        continue;
	    }
		add_DuLNode(dirp->d_name);
	}
	//关闭目录
	closedir(dp);
    display_DuLNode();
	tmp=head;
    while(1)
    {    
        printf("1.prior 2.next 3.exit:");
        scanf("%d",&i);
	    switch(i)
	    {
		     case 1:
		         {
					 display_prior_DuLNode();
				     break;
			     }
		     case 2:
		    	 {
					 display_next_DuLNode();
			    	 break;
		    	 }
		     case 3:
		    	 {
			    	 return 0;
			     }
		     default:
			     {
			    	 continue;
			     }
	     }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值