⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myfind.c.bak

📁 在unix下实现目录树的遍历以及一些相关的内容
💻 BAK
字号:
#include	<sys/types.h>
#include	<sys/stat.h>
#include	<dirent.h>
#include	<limits.h>
#include    <errno.h>
#include     "apue.h"
#include    <fcntl.h>
#include     <malloc.h>
#include     <string.h>

#define    MAXL 4096
typedef	int	Myfunc(const char *, const struct stat *, int);
				/* function type that's called for each filename */

static Myfunc	myfunc;
static Myfunc   myfunc2;
static Myfunc	myfunc3;
static int		myftw(char *, Myfunc *);
static int		dopath(Myfunc *);
static long	    nreg,nreg1, ndir, nblk, nchr, nfifo, nslink, nsock, ntot,total;
static char copy_argv[10][200],*name=NULL,*buff2=NULL;
static int copy_argc,length2;

int
main(int argc, char *argv[])
{
	int		ret,i,fd2;
    total=0;
	for(i=0;i<=argc-1;i++)
	   strcpy(copy_argv[i],argv[i]);//将argv数组拷到 copy_argv
    copy_argc=argc;   
    
	if(argc==2){
           ret = myftw(argv[1],myfunc);		/* does it all */
           total=0;
	         if ( (ntot = nreg + ndir + nblk + nchr + nfifo + nslink + nsock) == 0)
		           ntot = 1;		/* avoid divide by 0; print 0 for all counts */
	         printf("regular files  = %7ld, %5.2f %%\n", nreg,  nreg*100.0/ntot);
	         printf("directories    = %7ld, %5.2f %%\n", ndir,  ndir*100.0/ntot);
	         printf("block special  = %7ld, %5.2f %%\n", nblk,  nblk*100.0/ntot);
	         printf("char special   = %7ld, %5.2f %%\n", nchr,  nchr*100.0/ntot);
	         printf("FIFOs          = %7ld, %5.2f %%\n", nfifo, nfifo*100.0/ntot);
	         printf("symbolic links = %7ld, %5.2f %%\n", nslink,nslink*100.0/ntot);
	         printf("sockets        = %7ld, %5.2f %%\n", nsock, nsock*100.0/ntot);
	         printf("length of regular files large than %d=quantity is%7ld,percent si%5.2f %%\n ",MAXL,nreg1,nreg1*100.0/ntot);
          exit(ret);
        }
    else if((argc==4)&&((strcmp(argv[2],"-comp"))==0)){
        total=0;
        fd2=open(copy_argv[3],O_RDWR);
        length2=lseek(fd2,0,SEEK_END);//计算文件的长度 
        lseek(fd2,0,SEEK_SET);
        if((buff2=(char *)malloc(sizeof(char)*length2))==NULL){			               	 
   	 	      printf("the length2 is %ld",length2);
              err_sys("malloc error!!");
        }
 	 	if((read(fd2,buff2,length2))!=length2)//将文件的内容考到buff2缓冲区 
          err_sys("read error!!"); 
        close(fd2);  
        ret = myftw(argv[1], myfunc2);
        if(total==0)//当没有找到该文件时输出 
    	     	  printf("Not Find!!!!\n");
    }
    else if((argc>=4)&&((strcmp(argv[2],"-name"))==0)){
             total=0;
    	       ret = myftw(argv[1], myfunc3);
    	       if(total==0)
    	     	  printf("Not Find!!!!\n");
            }
            else 
       	   	    printf("input error!!!");  
}      

/*
 * Descend through the hierarchy, starting at "pathname".
 * The caller's func() is called for every file.
 */

#define	FTW_F	1		/* file other than directory */
#define	FTW_D	2		/* directory */
#define	FTW_DNR	3		/* directory that can't be read */
#define	FTW_NS	4		/* file that we can't stat */

static char	*fullpath;		/* contains full pathname for every file */

static int					/* we return whatever func() returns */
myftw(char *pathname, Myfunc *func)
{
    int len;       
	fullpath = path_alloc(&len);	/* malloc's for PATH_MAX+1 bytes */
									/* ({Prog pathalloc}) */
    strncpy(fullpath, pathname,len);	    /* initialize fullpath */
    fullpath[len-1]=0;
	return(dopath(func));
}
/*
 * Descend through the hierarchy, starting at "fullpath".
 * If "fullpath" is anything other than a directory, we lstat() it,
 * call func(), and return.  For a directory, we call ourself
 * recursively for each name in the directory.
 */
static int					/* we return whatever func() returns */
dopath(Myfunc* func)
{
	struct stat		statbuf;
	struct dirent	*dirp;
	DIR				*dp;
	int				ret;
	char			*ptr;

	if (lstat(fullpath, &statbuf) < 0)
		return(func(fullpath, &statbuf, FTW_NS));	/* stat error */

	if (S_ISDIR(statbuf.st_mode) == 0)
		return(func(fullpath, &statbuf, FTW_F));	/* not a directory */

	/*
	 * It's a directory.  First call func() for the directory,
	 * then process each filename in the directory.
	 */

	if ( (ret = func(fullpath, &statbuf, FTW_D)) != 0)
		return(ret);

	ptr = fullpath + strlen(fullpath);	/* point to end of fullpath */
	*ptr++ = '/';
	*ptr = 0;

	if ( (dp = opendir(fullpath)) == NULL)
		return(func(fullpath, &statbuf, FTW_DNR));
										/* can't read directory */

	while ( (dirp = readdir(dp)) != NULL) {
		if (strcmp(dirp->d_name, ".") == 0  ||
		    strcmp(dirp->d_name, "..") == 0)
				continue;		/* ignore dot and dot-dot */

		strcpy(ptr, dirp->d_name);	/* append name after slash */

		if ( (ret = dopath(func)) != 0)		/* recursive */
			break;	/* time to leave */
	}
	ptr[-1] = 0;	/* erase everything from slash onwards */

	if (closedir(dp) < 0)
		err_ret("can't close directory %s", fullpath);

	return(ret);
}
static int
myfunc(const char *pathname, const struct stat *statptr, int type)
{
    int fd,length;         
	switch (type) {
	case FTW_F:
		switch (statptr->st_mode & S_IFMT) {
		case S_IFREG:	{
                          nreg++; fd=open(pathname,O_WRONLY|O_CREAT,FILE_MODE);
                          if((length=lseek(fd,0,SEEK_END))<=MAXL)	
                              nreg1++;
                          close(fd);
                         	break;
                           }
		case S_IFBLK:	nblk++;		break;
		case S_IFCHR:	nchr++;		break;
		case S_IFIFO:	nfifo++;	break;
		case S_IFLNK:	nslink++;	break;
		case S_IFSOCK:	nsock++;	break;
		case S_IFDIR:
			err_dump("for S_IFDIR for %s", pathname);
					// directories should have type = FTW_D 
		}
		break;

	case FTW_D:
		ndir++;
		break;

	case FTW_DNR:
		err_ret("can't read directory %s", pathname);
		break;

	case FTW_NS:
		err_ret("stat error for %s", pathname);
		break;

	default:
		err_dump("unknown type %d for pathname %s", type, pathname);
	}

	return(0);
}
static int
myfunc2(const char *pathname, const struct stat *statptr, int type)
{
    int fd1,len;
    long length1,i;  
    char *buff1,*path,*buf2,*buf;
     /* length=strlen(pathname)*sizeof(char);
	path=(char *)malloc(length);
    for(i=length-1;pathname[i]!='/';i--) ;
	for(i=i+1,j=0;i<=length;i++,j++)
		path[j]=pathname[i];
	path[j]='\0';*/
     if(type==FTW_F){                     
             fd1=open(pathname,O_RDWR);
             length1=lseek(fd1,0,SEEK_END);//计算文件的长度 
             lseek(fd1,0,SEEK_SET);
             if(length1==length2){                 
                  if((buff1=(char *)malloc(sizeof(char)*length1))==NULL)
                     err_sys("malloc error!!");
                  if((read(fd1,buff1,length1))!=length1)//将文件的内容拷到buff1 
                     err_sys("read error!!"); 
                  for(i=0;i<=length2-1;i++)
                     if(buff1[i]!=buff2[i])
                            break;
                  if(i>=length2){
   	                   total++;
			           if((path=(char *)malloc(strlen(pathname)*sizeof(char)))==NULL) return 0;
                       for(len=strlen(pathname)-1;pathname[len]!='/'&&len>=0;len--) ;//查找pathname文件所在目录
		        	    for(i=0;i<=len;i++)//把文件pathname的目录名拷贝到path里
				        path[i]=pathname[i];
			             path[i]='\0';
			             buf2=path_alloc(&len);
			            if(getcwd(buf2,len)==NULL)	return 0;//用buf2保存当前程序所在的目录
			            if(chdir(path)==-1)		return 0;//切换到文件pathname所在的目录
		              	buf=path_alloc(&len);
		            	if(getcwd(buf,len)==NULL)	return 0;//用buf保存pathname所在的目录
			             if(chdir(buf2)==-1)		return 0;//切换回到程序运行所在的目录
			             for(i=strlen(pathname)-1;pathname[i]!='/';i--) ;//把pathname文件名提取出来
			             strcat(buf,&pathname[i]);
			             printf("%s\n",buf);            
                     }
                     free(buff1);
                     close(fd1);
                 }
             }
    
 	return(0);
}
static int
myfunc3(const char *pathname, const struct stat *statptr, int type)
{
    int i,len;  
    char *path,*ptr,*buf2,*buf;       
	if (type==FTW_F){ 
	     	for(i=3;i<=copy_argc-1;i++){//逐个比较文件名 
                       if((path=(char *)malloc(strlen(copy_argv[i])*sizeof(char)))==NULL)	
                            err_quit("malloc error\n");                  
                       strcpy(path,&pathname[strlen(pathname)-strlen(copy_argv[i])]);                        
                       if((strcmp(path,copy_argv[i]))==0){
                          total++;
                          if((path=(char *)malloc(strlen(pathname)*sizeof(char)))==NULL) return 0;
                          for(len=strlen(pathname)-1;pathname[len]!='/'&&len>=0;len--) ;//查找pathname文件所在目录
		        	      for(i=0;i<=len;i++)//把文件pathname的目录名拷贝到path里
				             path[i]=pathname[i];
			              path[i]='\0';
			              buf2=path_alloc(&len);
			              if(getcwd(buf2,len)==NULL)	return 0;//用buf2保存当前程序所在的目录
			              if(chdir(path)==-1)		return 0;//切换到文件pathname所在的目录
             	          buf=path_alloc(&len);
		            	  if(getcwd(buf,len)==NULL)	return 0;//用buf保存pathname所在的目录
			              if(chdir(buf2)==-1)		return 0;//切换回到程序运行所在的目录
			              for(i=strlen(pathname)-1;pathname[i]!='/';i--) ;//把pathname文件名提取出来
			              strcat(buf,&pathname[i]);
			              printf("%s\n",buf);
                        }
          }

  }
	return(0);
}
#ifdef PATF_MAX
static int pathmax=PATH_MAX;
#else 
static int  pathmax=0;
#endif
#define  SUSV3    200112L
static long posix_version=0;
#define  PATH_MAX_GUESS 1024
char * path_alloc(int *sizep)
{
     char *ptr;
     int size;
     if(posix_version==0)
        posix_version=sysconf(_SC_VERSION);
     if(pathmax==0){
          errno=0;
          if((pathmax=pathconf("/",_PC_PATH_MAX))<0){
               if(errno==0)
                   pathmax=PATH_MAX_GUESS;
               else 
                   err_sys("pathconf error for _PC_PATH_MAX");
            }
          else {
             pathmax++;
          }
      }
      if(posix_version<SUSV3)
         size=pathmax+1;
         else 
            size=pathmax;
      if((ptr=malloc(size))==NULL)
          err_sys("mallco error for pathname");
      if(sizep!=NULL)
          *sizep=size;
     return(ptr);
}            
                          













⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -