gpt4 book ai didi

c - 为什么这个烦人的波浪号 ~ 会出现在我的 char* 字符串中?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:35 24 4
gpt4 key购买 nike

我正在尝试使用 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 很可能是这里的罪魁祸首。

所以您的代码没有任何问题,任何工具都应该显示这些文件,因为它们确实存在。

关于c - 为什么这个烦人的波浪号 ~ 会出现在我的 char* 字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com