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

  • 本文关键字:打印 遍历 不应该 c
  • 更新时间 :
  • 英文 :


这可能只是我做错的语法问题,但我一生都想不通,所以如果这太"嘿,为我调试我的代码!"

相关代码:

struct dirent *readDir;
DIR *dir;
dir = opendir(name);
if(dir == NULL) {
    printf("No directory found with the name %sn", name);
} else {
    printf("directory named %s opened.n", name);
    while((readDir = readdir(dir)) != NULL) {
        if(readDir->d_name != ".." || readDir->d_name != ".") {
            printf("%sn", 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 ".."
}

以下有两个问题:

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

首先,你不能在 C 中以这种方式比较字符串......你实际上是在检查字符串文字的地址是否与 readDir->d_name 中的地址匹配。 您需要改用像 strcmp() 这样的函数。

其次,当你或这样的条件时,只需要一个是真的,就可以使整个表达式为真......而且由于d_name不能等于".."AND "." 同时,即使字符串比较确实如您(可能)预期的那样工作,整体表达式也将始终为 TRUE。

所以你需要这样的东西:

if (strcmp("..", readDir->d_name) && strcmp(".", readDir->d_name)) {

(因为当字符串不匹配strcmp()返回非零值,并且您需要不匹配两个字符串)。

最新更新