gpt4 book ai didi

C 目录遍历 - 打印不应该的目录名称

转载 作者:行者123 更新时间:2023-12-02 07:33:29 25 4
gpt4 key购买 nike

这可能只是我做错的语法问题,但我一辈子都弄不明白,所以如果这太“嘿,为我调试我的代码!”,我深表歉意

相关代码:

struct dirent *readDir;
DIR *dir;
dir = opendir(name);

if(dir == NULL) {
printf("No directory found with the name %s\n", name);
} else {
printf("directory named %s opened.\n", name);

while((readDir = readdir(dir)) != NULL) {
if(readDir->d_name != ".." || readDir->d_name != ".") {
printf("%s\n", readDir->d_name);
}
}
closedir(dir);
}

while 循环中的 if 条件似乎不起作用,这是它产生的输出:

directory named test opened.
file2
.
test2
file1
..

如果我没记错的话,if 语句应该过滤掉 .和 .. 目录,但事实并非如此。这样做的目标是成为递归目录遍历,但除非我能阻止它递归到 .和 .. 目录我无法继续前进。

基本上,我猜我不知道如何进行字符串比较?

最佳答案

C 不支持 '!=' 或 '==' 进行字符串比较。使用 strcmp();

if(readDir->d_name != ".." || readDir->d_name != ".") {

应该是

if(strcmp(readDir->d_name, "..") && strcmp(readDir->d_name, ".")) {
// d_name is not "." or ".."
}

关于C 目录遍历 - 打印不应该的目录名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369439/

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