在Debian中,你可以使用C語言的dirent.h
庫中的readdir
函數來讀取目錄中的文件和子目錄
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
dir = opendir("."); // 打開當前目錄
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "./%s", entry->d_name); // 構建文件的完整路徑
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
struct passwd *owner = getpwuid(file_stat.st_uid); // 獲取文件所有者
printf("File: %s, Owner: %s\n", entry->d_name, owner->pw_name);
}
closedir(dir);
return 0;
}
這個程序首先打開當前目錄,然后使用readdir
函數讀取目錄中的每個條目。對于每個條目,它使用stat
函數獲取文件的狀態信息,然后使用getpwuid
函數根據文件的UID獲取文件所有者。最后,它將文件名和所有者打印到控制臺。
要編譯此程序,請將其保存為list_owners.c
,然后在終端中運行以下命令:
gcc -o list_owners list_owners.c
這將生成一個名為list_owners
的可執行文件。運行此文件,你將看到當前目錄中所有文件的名稱及其所有者。