在C中实现ls -al命令 [英] Implementing the ls -al command in C

查看:95
本文介绍了在C中实现ls -al命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我的一个班级分配的一部分,我必须用C编写一个程序来复制ls -al命令的结果.我已经阅读了必要的材料,但仍无法获得正确的输出.到目前为止,这是我的代码,仅应打印出文件大小和文件名,但是其打印文件大小不正确.

As a part of an assignment from one of my classes, I have to write a program in C to duplicate the results of the ls -al command. I have read up on the necessary materials but I am still not getting the right output. Here is my code so far, its only supposed to print out the file size and the file name, but the file sizes its printing are not correct.

代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main(int argc, char* argv[])
{
    DIR *mydir;
    struct dirent *myfile;
    struct stat mystat;

    mydir = opendir(argv[1]);
    while((myfile = readdir(mydir)) != NULL)
    {
        stat(myfile->d_name, &mystat);    
        printf("%d",mystat.st_size);
        printf(" %s\n", myfile->d_name);
    }
    closedir(mydir);
}

这些是执行代码后的结果:

These are my results after executing the code:

[root@localhost ~]# ./a.out Downloads
4096 ..
4096 hw22.c
4096 ankur.txt
4096 .
4096 destination.txt

以下是正确的尺寸:

[root@localhost ~]# ls -al Downloads
total 20
drwxr-xr-x.  2 root root 4096 Nov 26 01:35 .
dr-xr-x---. 24 root root 4096 Nov 26 01:29 ..
-rw-r--r--.  1 root root   27 Nov 21 06:32 ankur.txt
-rw-r--r--.  1 root root   38 Nov 21 06:50 destination.txt
-rw-r--r--.  1 root root 1139 Nov 25 23:38 hw22.c

有人可以指出我的错误吗?

Can anyone please point out my mistake.

谢谢

安库尔

推荐答案

myfile->d_name是文件名而不是路径,因此,如果该文件名不起作用,则需要首先将文件名附加到目录"Downloads/file.txt"目录:

myfile->d_name is the file name not the path, so you need to append the file name to the directory "Downloads/file.txt" first, if it's is not the working directory:

char buf[512];    
while((myfile = readdir(mydir)) != NULL)
{
    sprintf(buf, "%s/%s", argv[1], myfile->d_name);
    stat(buf, &mystat);
....

关于为什么打印4096的原因,它是最后一次调用stat()时链接...的大小.

As to why it prints 4096 that is the size of the links . and .. from the last call to stat().

注意:您应该分配一个足够大的缓冲区来容纳目录名,文件名NULL字节和分隔符,诸如此类

Note: you should allocate a buffer large enough to hold the directory name, the file name the NULL byte and the separator, something like this

strlen(argv[1]) + NAME_MAX + 2;

这篇关于在C中实现ls -al命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆