I’m trying to find a file using BFS and recursion , where given a directory and a file , the algorithm needs to check the given directory or all its sub directories .
Now, when I check a directory, sometimes I have an annoying ~ tilde that pops up at the end of the char* string . I’ve checked with some printf-S and came to a conclusion that the ~ is actually a part of the file-name .
How could that be? Sid I do something wrong?
Here is part of the recursion :
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);
}
And from terminal I hit ./exer4 check david.txt , and got :
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~
Having a tilde (~) as a suffix means the file is an automatic backup, for instance Emacs tends to create these. Since your example shows tilde-suffixed text (
.txt) files, it seems very likely that Emacs is the culprit here.So there’s nothing wrong with your code, any tool should show these files since they’re actually there.