0

我正在尝试使用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~
4

2 回答 2

4

波浪号 (~)作为后缀意味着该文件是自动备份,例如Emacs 倾向于创建这些. 由于您的示例显示了波浪号后缀的文本 ( .txt) 文件,因此 Emacs 很可能是这里的罪魁祸首。

所以你的代码没有问题,任何工具都应该显示这些文件,因为它们实际上就在那里。

于 2012-06-15T09:01:17.550 回答
1

您是在使用vi还是Vim作为编辑器?这些文件(其名称以 a 结尾~)是由vi.

于 2012-06-15T09:01:27.543 回答