我正在嘗試用它的一些標志重寫 ls 函式,目前我正在實作 [-l] 標志,但是關于原始 ls 和 lstat 權限的輸出是不同的
這是我的代碼
void mx_strmode(mode_t mode, char * buf) {
const char chars[] = "rwxrwxrwx";
for (size_t i = 0; i < 9; i ) {
buf[i] = (mode & (1 << (8-i))) ? chars[i] : '-';
}
buf[9] = '\0';
}
int main(int ac, char **av) {
t_flags flags = mx_get_flags(ac, av);
char *dir_name = get_dir_name(ac, av);
DIR *dir;
struct dirent *entry;
dir = opendir(dir_name);
if (!dir) {
perror("diropen");
exit(1);
};
struct stat s_stat;
while ((entry = readdir(dir)) != NULL) {
lstat(entry->d_name, &s_stat);
char buf_perm[10];
mx_strmode(s_stat.st_mode, buf_perm);
printf("%s %s\n", buf_perm , entry->d_name);
};
closedir(dir);
}
這是我從 ls 和我的程式中得到的。我正在打開不包含我的可執行檔案的目錄(可能是問題的根源)
>drwxr-xr-x 3 fstaryk 4242 102 Jan 3 17:27 .
>drwxr-xr-x 11 fstaryk 4242 374 Jan 18 17:40 ..
>-rw-r--r-- 1 fstaryk 4242 4365 Jan 18 17:40 main.c
>rwxr-xr-x .
>rwx------ ..
>rwx------ main.c
uj5u.com熱心網友回復:
正如您從添加評論中建議的錯誤檢查中發現的那樣,您遇到了“沒有這樣的檔案或目錄”的問題。這是因為從當前作業目錄開始lstat()決議物件中的檔案名等相對路徑,這不是您嘗試列出檔案的目錄。struct dirent
幸運的是,現代 unix/linux 系統有一個函式fstatat()可以讓你指定一個目錄作為相對路徑的基礎,你可以從一個DIR帶有dirfd().
使用它的簡化示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
int main(void) {
DIR *d = opendir("test/");
if (!d) {
perror("opendir");
return EXIT_FAILURE;
}
int dfd = dirfd(d); // Get the directory file descriptor for use with fstatat()
if (dfd < 0) {
perror("dirfd");
closedir(d);
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(d))) {
if (entry->d_name[0] == '.') {
// Skip dotfiles
continue;
}
struct stat s;
// Resolve filenames relative to the directory being scanned
// and don't follow symlinks to emulate lstat()'s behavior
if (fstatat(dfd, entry->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
perror("fstatat");
closedir(d);
return EXIT_FAILURE;
}
printf("%s: %ld\n", entry->d_name, (long)s.st_size);
}
closedir(d);
return 0;
}
在缺少這些*at()功能的舊作業系統上,您必須求助于創建一個包含目錄名 檔案名(Withsnprintf()或其他)的字串,并將其用作lstat().
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415357.html
標籤:
