我正在尝试使用BFS
和递归查找文件,在给定目录和文件的情况下,算法需要检查给定目录或其所有子目录。
现在,当我检查目录时,有时会在字符串~
末尾弹出一个恼人的波浪号。char*
我已经检查了一些printf-S
并得出结论,这~
实际上是 file-name 的一部分。
怎么可能?是不是我做错了什么?
这是递归的一部分:
int scanner(char *dirname,char *entries , char * directory , char * file)
{
struct stat st;
/* scan the directory and store the entries in a buffer */
DIR *dir;
struct dirent *ent;
int count=1;
char name[256];
if ((dir = opendir(dirname)) == NULL)
{
perror("Unable to open directory");
return(0);
}
while ((ent = readdir(dir)) != NULL)
count++;
rewinddir(dir);
// here we copy all the file-names from the directory into the buffer
// we copy all the names using sprintf and strcpy
while ((ent = readdir(dir)) != NULL)
{
strcpy(name,ent->d_name);
if (strcmp(name , file) == 0 )
{
printf("\nFile was found !!! in first IF\n");
printf("\n-----------------------------------------------------------------------\n");
if (stat(name, &st) < 0) {
perror(name);
putchar('\n');
continue;
}
printfile(&st , name);
printf("\nStringer 'name' is : %s" , name);
printf("\nThe length of %s is %d" , name , strlen(name));
}
else // try
{
int length = strlen(name);
char try[length+2];
strcpy(try,name);
try[length+1] = '~';
try[length+2] = '\0';
printf("\nThe 'name' is : %s" , name);
printf("\nThe length of %s is %d" , name , strlen(name));
printf("\nPrint try %s\n" , try);
if (strcmp(try , file) == 0 )
printf("\nFile was found !!! in second IF\n");
}
sprintf(entries,"%s",name);
entries = entries+strlen(name)+1;
printf("\nStringer name :%s" , name);
count++;
}
if (closedir(dir) != 0)
perror("Unable to close directory");
return(count);
}
从terminal
我打./exer4 check david.txt
,得到:
The 'name' is : ..
The length of .. is 2
Print try ..
Stringer name :..
The 'name' is : .
The length of . is 1
Print try .
Stringer name :.
The 'name' is : insideCheck
The length of insideCheck is 11
Print try insideCheck
Stringer name :insideCheck
The 'name' is : david.txt~
The length of david.txt~ is 10
Print try david.txt~
Stringer name :david.txt~
The 'name' is : doc.txt~
The length of doc.txt~ is 8
Print try doc.txt~