我正在尝试用bash(linux)用C语言编写一个简单的“ ls”脚本。我设法编写了一个脚本,该脚本为我提供了有关给定目录中文件的所有我需要的信息,但是由于某种原因,它仅适用于当前的“”。目录,而不用于其他任何目录。对于其他任何目录,它都在其中显示文件(例如,文件名正确),但没有显示正确的统计信息(有关文件的其他信息)。我不知道如何修复它。作为指导,我使用了http://man7.org/linux/man-pages/man2/stat.2.html。
我的脚本:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
int opt;
DIR *dir;
struct dirent *poz;
char *katalog;
char *nazwa, *user_n, *grupa_n, *rozmiar_n, *numer_iw, *typ_p, *output_p;
nazwa = "Name"; user_n = "UID"; grupa_n = "GID", rozmiar_n = "Size"; numer_iw = "I-node no."; typ_p = "Type";
struct stat sb;
if (argc == 2) {
katalog = argv[1];
dir = opendir(katalog);
printf("%11s %11s %11s %11s %11s %15s \n", typ_p, user_n, grupa_n, numer_iw, rozmiar_n, nazwa);
if (dir) { while ((poz = readdir(dir)) != NULL) {
if (lstat(poz->d_name, &sb) == 1) {
perror("lstat");
exit(EXIT_FAILURE);
}
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: output_p = "block device"; break;
case S_IFCHR: output_p = "character device"; break;
case S_IFDIR: output_p = "directory"; break;
case S_IFIFO: output_p = "FIFO"; break;
case S_IFLNK: output_p = "symlink"; break;
case S_IFREG: output_p = "file"; break;
case S_IFSOCK: output_p = "socket"; break;
default: output_p = "unknown"; break;
}
printf("%11s %11llu %11llu %11llu %11llu %15s \n", output_p, (unsigned long long) sb.st_gid,
(unsigned long long) sb.st_uid, (unsigned long long) sb.st_ino, (unsigned long long) sb.st_size, poz->d_name);
}
closedir(dir);
}
}
return (0);
}
示例执行:
./a.out .
工作正常(输出):
Type UID GID I-node no. Size Name
file 1000 1000 274621 248 sample_file2
file 1000 1000 274603 36 sample_file
file 1000 1000 272921 12776 a.out
file 1000 1000 274616 1859 script.c
directory 1000 1000 295524 4096 .
directory 1000 1000 269568 4096 ..
directory 1000 1000 295526 4096 sample_dir
示例执行:
./a.out sample_dir
出现错误(错误信息,例如所有文件/目录的文件类型或大小错误):
Type UID GID I-node no. Size Name
directory 1000 1000 295524 4096 .
directory 1000 1000 295524 4096 sample_file_inside_dir
directory 1000 1000 295524 4096 sample_dir_inside_dir
directory 1000 1000 295524 4096 sample_file_2
directory 1000 1000 269568 4096 ..
我看不到此错误在哪里...为什么stat()仅适用于当前目录?有办法改变吗?
谢谢您的时间。 B