在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
的可执行文件。运行此文件,你将看到当前目录中所有文件的名称及其所有者。