在Ubuntu中,你可以使用readdir函數來讀取目錄中的文件和子目錄。但是,readdir本身并不提供文件所有者的信息。要獲取文件所有者信息,你需要使用stat函數。
以下是一個簡單的示例,展示了如何使用readdir和stat函數來獲取目錄中文件的名稱和所有者信息:
#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");
return 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 EXIT_SUCCESS;
}
這個程序首先打開當前目錄(.),然后使用readdir函數讀取目錄中的每個條目。對于每個條目,我們使用snprintf函數構建文件的完整路徑,然后使用stat函數獲取文件的狀態信息。最后,我們使用getpwuid函數根據文件的UID查找文件所有者,并將結果打印到屏幕上。
編譯并運行此程序,你將看到類似以下的輸出:
File: example.txt, Owner: your_username
File: another_file.txt, Owner: another_user
...
請注意,這個示例僅適用于C語言。如果你需要在其他編程語言中實現類似的功能,請查閱相應語言的文檔。