用法:whereis pathnanme .文件后缀名
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <limits.h>
#include <errno.h>
#include <string.h>
static int dopath();
void checkfile();
char *path_alloc(int *sizep);
char *fullpath;
char *filename;
int main(int argc, char *argv[])
{
if(argc != 3)
exit(1);
int pathlen, filelen;
fullpath = path_alloc( &pathlen );
strncpy(fullpath, argv[1], pathlen);//如果argv[1]长度大于pathlen,那么只有pathlen个字符复制到fullpath,它的结果将不会以NULL字节为结尾.
fullpath[pathlen - 1] = 0;
filename = path_alloc( &filelen );
strncpy(filename, argv[2], filelen);
filename[filelen - 1] = 0;
dopath();
return 0;
}
static int dopath()
{
struct stat statbuf;
struct dirent *dirp;
DIR *dp;
char *ptr;
if(lstat(fullpath, &statbuf)<0)
return 1;
if(S_ISDIR(statbuf.st_mode)==0)
checkfile();
ptr=fullpath + strlen(fullpath);
*ptr++ = '/';
*ptr = 0;
if((dp=opendir(fullpath)) == NULL)
return 1;
while((dirp=readdir(dp)) != NULL)
{
if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
continue;
strcpy(ptr, dirp->d_name);
dopath();
}
*--ptr = 0;
if(closedir(dp) < 0) printf("can't close directory %s\n",fullpath);
return 0;
}
void checkfile()
{
int i = 0;
char *p1 = fullpath;
p1 = p1 + strlen(fullpath)- strlen(filename);
if(strcmp(filename, p1) == 0)
printf("%s\n", fullpath);
}
#ifdef PATH_MAX
static int pathmax = PATH_MAX;
#else
static int pathmax = 0;
#endif
#define SUSV3 200112L
static long posix_version = 0;
/* If PATH_MAX is indeterminate, no guarantee this is adequate */
#define PATH_MAX_GUESS 1024
char *
path_alloc(int *sizep) /* also return allocated size, if nonull */
{
char *ptr;
int size;
if (posix_version == 0)
posix_version = sysconf(_SC_VERSION);
if (pathmax ==0) /* first time through */
{
errno = 0;
if ((pathmax = pathconf("/", _PC_PATH_MAX)) < 0)
{
if (errno == 0)
pathmax = PATH_MAX_GUESS; /* it's indeterminate */
else
printf("pathconf error for _PC_PATH_MAX");
}
else
pathmax++; /* add one since it's relative to root */
}
if (posix_version < SUSV3)
size = pathmax + 1;
else
size = pathmax;
if ((ptr = malloc(size)) == NULL)
printf("malloc error for pathname");
if(sizep != NULL)
*sizep = size;
return(ptr);
}

浙公网安备 33010602011771号