你好,游客 登录 注册 搜索
背景:
阅读新闻

Ubuntu 编写自己的ls命令

[日期:2012-07-09] 来源:Linux社区  作者:lr-ting [字体:大 中 小]

4.结果显示

查看文件(display_file)结果:

linux@Ubuntu:~/test$ ./a.out stat.c 
-rw-r--r-- 1 linux linux 15316 2012-06-19 14:05 stat.c

查看文件夹(display_dir)结果:

linux@ubuntu:~/test$ ./a.out .
-rw-r--r-- 1 linux linux 1508 2012-06-19 14:40 ls.c
-rw-r--r-- 1 linux linux 1635 2012-06-19 14:12 ls-bak.c
-rwxrw-rw- 1 linux linux 1777 2012-06-19 15:02 ls_t.c
-rw-r--r-- 1 linux linux 15316 2012-06-19 14:05 stat.c
-rwxr-xr-x 1 linux linux 7632 2012-06-19 15:14 a.out

附:ls 命令实现的完整代码

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

int display_file(char *path, char *filename)
{
    struct stat st;
    int i;
    struct passwd *pw;
    struct group *gr;
    struct tm *tm;
    stat(path, &st);

    switch(st.st_mode & S_IFMT)    
    {
    case S_IFREG:  printf("-");    break;
    case S_IFDIR:  printf("d");    break;
    case S_IFLNK:  printf("l");    break;
    case S_IFBLK:  printf("b");    break;
    case S_IFCHR:  printf("c");    break;
    case S_IFIFO:  printf("p");    break;
    case S_IFSOCK: printf("s");    break;
    }

    for(i = 8; i >= 0; i--)
    {    
        if(st.st_mode & (1 << i))
        {
            switch(i%3)
            {
            case 2: printf("r"); break;
            case 1: printf("w"); break;
            case 0: printf("x"); break;
            }
        }
        else
            printf("-");
    }

    pw = getpwuid(st.st_uid);
    gr = getgrgid(st.st_gid);

    printf("%2d %s %s %4ld", st.st_nlink, pw->pw_name, gr->gr_name, st.st_size);

    tm = localtime(&st.st_ctime);
    printf(" %04d-%02d-%02d %02d:%02d",tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);

    printf(" %s\n", filename);

    return 0;
}

int display_dir(char *dirname)
{
    DIR *dir;
    struct dirent *dirent;
    struct stat st;
    char buf[1024];

    dir = opendir(dirname);
    while((dirent = readdir(dir)) != NULL)
    {
        strcpy(buf, dirname);
        strcat(buf, "/");
        strcat(buf, dirent->d_name);
        if(stat(buf, &st))
        {
            perror("stat");
            return -1;
        }

        if(dirent->d_name[0] != '.')
            display_file(buf, dirent->d_name);
    }
}

int main(int argc, char **argv)
{
    struct stat st;
    char buf[1024];

    if(stat(argv[1], &st) < 0)
    {
        perror("stat");
        return -1;
    }

    if((st.st_mode & S_IFMT) == S_IFDIR)
        display_dir(argv[1]);
    else
        display_file(argv[1], argv[1]);

    return 0;
}

关于如何显示文件颜色的相关介绍可以参看: http://www.linuxidc.com/Linux/2012-07/64782.htm

效果图如下:

linux
相关资讯       ls 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款