在 CentOS 中,使用 readdir 處理符號鏈接需要編寫一個程序來讀取目錄內容并檢查每個條目是否為符號鏈接
sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel
read_dir_symlinks.c 的 C 文件,并添加以下代碼:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
char *dir_path = argv[1];
DIR *dir = opendir(dir_path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
struct stat path_stat;
if (lstat(path, &path_stat) == -1) {
perror("lstat");
continue;
}
if (S_ISLNK(path_stat.st_mode)) {
printf("Symlink: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
這段代碼會讀取指定目錄中的所有條目,并使用 lstat() 函數獲取每個條目的狀態。如果條目是符號鏈接,它將打印出 “Symlink” 和符號鏈接的名稱。
gcc -o read_dir_symlinks read_dir_symlinks.c
./read_dir_symlinks /path/to/directory
程序將輸出目錄中所有符號鏈接的名稱。
注意:這個示例僅適用于 C 語言。如果你需要在其他編程語言中實現類似的功能,請查閱相應語言的目錄讀取和符號鏈接處理文檔。