ls -al的“总计”是什么?

时间:2019-04-03 20:57:33

标签: c format ls stat

我受命模仿命令ls -alU --time-style=long-iso。虽然我快要失望了,但我不太了解总的第一印象是什么。我知道它使用的总块数* 2或类似的值,但我不知道该数字来自何处以及使用stat在哪里找到?

代码

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <grp.h>
#include <time.h>
#include <pwd.h>
#include <errno.h>
#include <string.h>

int main(void)
{
    DIR *mydir;
    struct dirent *myfile;
    struct stat myStat;
    struct passwd *pwd;
    int s;
    struct tm lt;
    char buf[1024];
    struct group *gf;
    mydir = opendir("./");

    while((myfile = readdir(mydir)) != NULL)
    {
        stat(myfile->d_name, &myStat);
        if((stat(myfile->d_name, &myStat) ) == 0){
            pwd = getpwuid(myStat.st_uid);
        }
        gf = getgrgid(myStat.st_gid);
        time_t t = myStat.st_mtime;
        localtime_r(&t, &lt);
        char timebuf[80];
        char timebuf2[80];

        strftime(timebuf, sizeof(timebuf), "%F", &lt);
        strftime(timebuf2, sizeof(timebuf2), "%R", &lt);
        printf( (S_ISDIR(myStat.st_mode)) ? "d" : "-");
        printf( (myStat.st_mode & S_IRUSR) ? "r" : "-");
        printf( (myStat.st_mode & S_IWUSR) ? "w" : "-");
        printf( (myStat.st_mode & S_IXUSR) ? "x" : "-");
        printf( (myStat.st_mode & S_IRGRP) ? "r" : "-");
        printf( (myStat.st_mode & S_IWGRP) ? "w" : "-");
        printf( (myStat.st_mode & S_IXGRP) ? "x" : "-");
        printf( (myStat.st_mode & S_IROTH) ? "r" : "-");
        printf( (myStat.st_mode & S_IWOTH) ? "w" : "-");
        printf( (myStat.st_mode & S_IXOTH) ? "x" : "-");
        printf(" ");
        printf("%ld ", myStat.st_nlink);
        if(pwd != 0){
            printf("%s %s %ld\t%s %s %s\n", pwd->pw_name, gf->gr_name, (long)myStat.st_size, timebuf, timebuf2, myfile->d_name);
        }else  {

            printf("%d %s %ld\t%s %s %s\n", myStat.st_uid, gf->gr_name, (long)myStat.st_size, timebuf, timebuf2, myfile->d_name);
            printf("\n");
        } 
    }
    closedir(mydir);
}

当前输出

drwxr-xr-x 3 user user    46 2019-04-03 21:17 .
drwxr-xr-x 3 user root    19 2019-04-03 18:33 ..
drwxr-xr-x 2 user user     6 2019-04-03 18:34 .che
-rw-r--r-- 1 user user  1895 2019-04-03 21:17 lsdir.c
-rwxr-xr-x 1 user user 13304 2019-04-03 21:17 lsdir

期望的输出

total 20
drwxr-xr-x 3 user user    46 2019-04-03 21:17 .
drwxr-xr-x 3 user root    19 2019-04-03 18:33 ..
drwxr-xr-x 2 user user     6 2019-04-03 18:34 .che
-rw-r--r-- 1 user user  1895 2019-04-03 21:17 lsdir.c
-rwxr-xr-x 1 user user 13304 2019-04-03 21:17 lsdir

0 个答案:

没有答案