小编ank*_*000的帖子

在C中实现ls -al命令

作为我的一个类的赋值的一部分,我必须在C中编写一个程序来复制ls -al命令的结果.我已经阅读了必要的材料,但我仍然没有得到正确的输出.这是我的代码到目前为止,它只应打印出文件大小和文件名,但其打印的文件大小不正确.

码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

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

[root@localhost ~]# ./a.out Downloads
4096 ..
4096 hw22.c
4096 ankur.txt
4096 .
4096 destination.txt
Run Code Online (Sandbox Code Playgroud)

这是正确的尺寸:

[root@localhost ~]# ls -al Downloads
total 20
drwxr-xr-x.  2 root root 4096 Nov 26 01:35 .
dr-xr-x---. …
Run Code Online (Sandbox Code Playgroud)

c linux ls file stat

16
推荐指数
2
解决办法
6万
查看次数

标签 统计

c ×1

file ×1

linux ×1

ls ×1

stat ×1