C Ubuntu递归列出文件,检测符号链接

C Ubuntu递归列出文件,检测符号链接,c,linux,symlink,stat,dirent.h,C,Linux,Symlink,Stat,Dirent.h,我正在尝试使用dirent.h递归地列出我的本地文件系统。为了防止跟踪sym链接,我使用了sys/stat.h标题。在以下内容中,您可以找到我的SSCCE程序 /** * coding: utf-8 * * Copyright (C) 2013, Niklas Rosenstein * * listdir.c - List up directories and file-content recursively. */ #include <stdio.h> #includ

我正在尝试使用
dirent.h
递归地列出我的本地文件系统。为了防止跟踪sym链接,我使用了
sys/stat.h
标题。在以下内容中,您可以找到我的SSCCE程序

/**
 * coding: utf-8
 *
 * Copyright (C) 2013, Niklas Rosenstein
 *
 * listdir.c - List up directories and file-content recursively.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

void list_dir(const char* directory_name) {
    DIR* directory_handle = opendir(directory_name);
    if (directory_handle == NULL) {
        fprintf(stderr, "Could not open directory %s.\n", directory_name);
        return;
    }

    char buffer[1024];
    struct dirent* dentry;
    int directory_name_length = strlen(directory_name);

    memcpy(buffer, directory_name, directory_name_length);
    buffer[directory_name_length] = '/';

    while ((dentry = readdir(directory_handle)) != NULL) {
        char* name = dentry->d_name;
        int length = strlen(name);

        // Skip the dotted elements.
        if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue;

        // Concatenate the directory name with the element name.
        memcpy(buffer + directory_name_length + 1, name, length);
        buffer[directory_name_length + 1 + length] = 0;

        printf("%s\n", buffer);

        // Proceed recursively if the element is a directory.
        struct stat s;
        if (stat(buffer, &s) != 0) {
            fprintf(stderr, "WARNING: stat() failed on %s\n", buffer);
            continue;
        }

        mode_t mode = s.st_mode;
        if (mode & S_IFDIR && !(mode & S_IFLNK)) {
            list_dir(buffer);
        }

    }
    closedir(directory_handle);
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "Expected exactly 2 arguments.\n");
        return -1;
    }
    list_dir(argv[1]);
    return 0;
}
这一行不能完全正确:
if(mode&S\u IFDIR&&!(mode&S\u IFLNK)){
。这可能是
stat()
函数的问题,还是我在这里遗漏了一些明显的东西

这是我的终端在调用
/listdir/usr/bin/X11
,按
^C
大约一秒钟后停止程序后的图片


尝试
lstat
而不是
stat
:后者在符号链接上执行时,返回有关其目标的信息(最后一个,它不是符号链接)

S_-IFDIR
S_-iflink
不应被当作独占位标志使用。对于目录,使用
S_-ISDIR(模式)
;对于符号链接,您无需测试:
lstat
不会将符号链接报告为目录,当您只想跳过符号链接时,这就足够了

/usr/bin/X11/
    X11/ -> .