简体   繁体   English

在C中实现ls命令

[英]Implementing the ls command in C

I'm trying to implement the ls command in c with as many flags as possible, but i'm having issues with getting the correct Minor and Major of the files, here's an example of what i did. 我正在尝试使用尽可能多的标志在c中实现ls命令,但是我在获取正确的Minor和Major文件中遇到问题,这是我所做的示例。

> ls -l ~/../../dev/tty
crw-rw-rw- 1 root tty 5, 0 Nov 25 13:30 

this is the normal ls command as you can see the Major is 5, and Minor is 0. my program shows the following : 这是正常的ls命令,您可以看到Major为5,Minor为0。我的程序显示以下内容:

Minor: 6
Major: 0

i'm still a beginner so i didn't really understand the issue here, this is what i did so far (the program is not identical to the ls command yet, but only shows information about a file). 我仍然是一个初学者,所以我在这里还不是很了解这个问题,这是我到目前为止所做的(该程序与ls命令还不相同,只显示有关文件的信息)。

int disp_file_info(char **argv)
{
 struct stat sb;

 stat(argv[1], &sb);
 printf("Inode: %d\n", sb.st_ino);
 printf("Hard Links: %d\n", sb.st_nlink);
 printf("Size: %d\n", sb.st_size);
 printf("Allocated space: %d\n", sb.st_blocks);
 printf("Minor: %d\n", minor(sb.st_dev));
 printf("Major: %d\n", major(sb.st_dev));
 printf("UID: %d\n", sb.st_uid);
 printf("GID: %d\n", sb.st_gid);
 }

for now this is only to obtain certain information about a file, everything seems to be correct when compared with the ls command except for Minor and Major. 现在,这仅是为了获取有关文件的某些信息,与ls命令相比,除Minor和Major外,其他一切似乎都是正确的。

You are using st_dev , which is the device on which the file resides . 您正在使用st_dev ,即文件所在的设备。 You want st_rdev , which is the device the special file "is"/represents. 您需要st_rdev ,这是特殊文件“是” /代表的设备。 (You should first check whether the file is a device node, though.) (不过,您首先应该检查文件是否是设备节点。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM