c - 在 C 中实现 ls -al 命令

标签 c linux file ls stat

作为我的一个类(class)作业的一部分,我必须用 C 语言编写一个程序来复制 ls -al 命令的结果。我已经阅读了必要的 Material ,但仍然没有得到正确的输出。到目前为止,这是我的代码,它只应该打印出文件大小和文件名,但它打印的文件大小不正确。

代码:

#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);
}

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

[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

谁能指出我的错误

谢谢,

安库尔

最佳答案

myfile->d_name 是文件名而不是路径,因此您需要先将文件名附加到目录 "Downloads/file.txt" 中,如果它不是工作目录:

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

至于为什么它打印 4096 这是链接 ... 从最后一次调用 stat ()

注意:你应该分配一个足够大的缓冲区来容纳目录名、文件名、NULL 字节和分隔符,像这样

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

关于c - 在 C 中实现 ls -al 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554150/

相关文章:

c - 该程序通过了我大学的评分器(所有测试用例),但我的电脑出现段错误

c - C 中的 Salted sha512,无法与 Symfony2 的 FOSUserBundle 同步

Linux 端点上的 Node.js 适用于 'api//method' 但不适用于 'api/method'

java - 我如何知道哪些进程正在使用 Windows 中 Java 下的文件?

java - 将/libs/*.jar打包成一个jar?

c - udp 连接套接字上的 ICMP "destination unreachable"数据包

c - Linux 内核模块文件关闭不太正确

linux - 如何在 Linux 中 grep 特定时间戳范围内的日志文件内容?

linux - Docker 克隆 - 权限被拒绝

asp.net - 根据需要在服务器中生成并提供文件。在不消耗太多资源的情况下最好的方法是什么?