我正在尝试使用递归列出我的本地文件系统dirent.h
。为了防止遵循符号链接,我使用了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;
}
我只是无法正确检测符号链接。当它遇到一个符号链接时,链接到它的父目录,它会继续下去。我的系统上似乎有几个这样的文件夹,例如。/usr/bin/X11
:
/usr/bin/X11/
X11/ -> .
此行不能完全正确:if (mode & S_IFDIR && !(mode & S_IFLNK)) {
. 可能是该stat()
功能的问题还是我在这里遗漏了一些明显的东西?
这是调用 后我的终端的图片,./listdir /usr/bin/X11
大约一秒钟后按 停止程序^C
。