Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C directory traversal - printing directory names it shouldn't be

Tags:

c

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?


1 Answers

C does not support '!=' or '==' for string comparison. Use strcmp();

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

Should be

if(strcmp(readDir->d_name, "..") && strcmp(readDir->d_name, ".")) {
    // d_name is not "." or ".."
}
like image 53
Charlie Burns Avatar answered Dec 23 '25 03:12

Charlie Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!