我想做一个可以查找文件的程序,代码如下,为什么运行的时候只能有一个子目录,如果在子目录中还有子目录的话就会报错,还有切换到别的路径去执行这个程序的话就出现了一些莫名其妙的输出。
这几天被这个弄得烦死了,大家帮帮忙哦。^_^
#include <stdio.h>
#include <string.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/types.h>
int search(char *, char *, char *);
char pwd[80]; //存放路径
int num = 0;
//char *str=(char *)malloc(256);
int main(int args, char **argv)
{
char *str = (char *)malloc(256);
//char str[256];
memset(str, 0, sizeof(str));
if(args < 2){
printf("请输入要查找的文件\n");
return;
}
else if(args > 2){
printf("只能查找一个文件\n");
return;
}
else{
getcwd(pwd, sizeof(pwd)); //跟踪当前目录
printf("%s\n", pwd);
if(!search(pwd, argv[1], str))
printf("找不到你所需要的文件\n");
}
free(str);
}
int search(char *dirname, char *filename, char *str)
{
DIR *dir;
struct dirent *ptr;
struct stat buf;
dir = opendir(dirname);
while( (ptr = readdir(dir)) != NULL)
{
lstat(ptr->d_name, &buf);
if(!strcmp(".", ptr->d_name) || !strcmp("..", ptr->d_name))
continue;
if(S_ISDIR(buf.st_mode))
{
strcat(strcat(str, "/"), ptr->d_name);
printf("%s\n", str); //跟踪当前的str
search(ptr->d_name, filename, str); //在子目录中继续查找
}
else if(!strcmp(ptr->d_name, filename))
{
printf("%s/%s\n", str, ptr->d_name);
num++;
}
else
continue;
}
return num;
}
[ 此贴被XChinux在2005-09-06 13:37重新编辑 ]