我尝试使用BFS和递归来查找文件,在给定目录和文件的情况下,算法需要检查给定目录或其所有子目录。
现在,当我检查一个目录时,有时会在~字符串的末尾弹出一个恼人的char*波浪号。我与一些printf-S进行了核对,得出结论~实际上是文件名的一部分。
怎么会这样?我做错什么了?
以下是递归的一部分:

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~

最佳答案

tilde (~)作为后缀意味着文件是自动备份,例如Emacs tends to create these。由于您的示例显示了带波浪号后缀的文本(.txt)文件,因此Emacs很可能是罪魁祸首。
所以你的代码没有问题,任何工具都应该显示这些文件,因为它们确实存在。

09-17 04:34