Search code examples
clinuxls

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.

> 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 :

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).

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.


Solution

  • You are using st_dev, which is the device on which the file resides. You want st_rdev, which is the device the special file "is"/represents. (You should first check whether the file is a device node, though.)