2

This is probably just a syntax thing that I'm doing wrong, but I can't for the life of me figure it out, so I apologize if this is too "HEY DEBUG MY CODE FOR ME!"

Relevant code:

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);
}

The if condition in the while loop doesn't seem to work, here's the output it produces:

directory named test opened.
file2
.
test2
file1
..

If I'm not mistaking, the if statement should filter out the . and .. directories, but it doesn't. The goal of this is to be a recursive directory traversal, but unless I can keep it from recursing into the . and .. directories I can't really move on.

Basically, I don't know how to do string comparing I guess?

4

2 回答 2

5

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

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

应该

if(strcmp(readDir->d_name, "..") && strcmp(readDir->d_name, ".")) {
    // d_name is not "." or ".."
}
于 2013-10-14T21:15:59.680 回答
2

以下有两个问题:

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

首先,您不能在 C 中以这种方式比较字符串...您实际上是在检查字符串文字的地址是否与readDir->d_name. 您需要使用类似的功能strcmp()

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

所以你需要类似的东西:

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

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

于 2013-10-14T21:25:42.203 回答