linux编程实践4(实现ls -l命令)

下面是ls -l的简单实现,还有很多不完善的地方,如没有进行排序等。


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

void do_ls(char *);
void do_stat(char *);
void show_file_info(char *, struct stat *);
void transfer_mode(mode_t, char mode_str[]);
char * uid_to_name(uid_t uid);
char * gid_to_name(gid_t gid);

int main(int argc, char **argv)
{
    if(argc == 1)
        do_ls(".");
    else
        while(--argc)
        {
            printf("%s:\n", *++argv);
            do_ls(*argv);
        }

    return 0;
}

void do_ls(char *path)
{
    char * filename;
    DIR * dir_ptr;
    struct dirent * dirent_ptr;

    if((dir_ptr = opendir(path)) == NULL)
    {
        perror("opnedir");
        exit(1);
    }

    while((dirent_ptr = readdir(dir_ptr)) != NULL)
    {
        do_stat(dirent_ptr->d_name);
    }
    closedir(dir_ptr);

}

void do_stat(char *filename)
{
    struct stat info;
    if(stat(filename, &info) == -1)
        perror("stat");
    else
        show_file_info(filename, &info);
}

void show_file_info(char *filename, struct stat *info)
{
    char mode_str[11];
    transfer_mode(info->st_mode, mode_str);
    printf("%s", mode_str);

    printf("%4d", (int)info->st_nlink);
    printf("%8s", uid_to_name(info->st_uid));
    printf("%8s", gid_to_name(info->st_gid));
    printf("%8ld", info->st_size);
    printf("%15.12s", ctime(&info->st_mtime) + 4);
    printf("%15s\n", filename);

}

char * uid_to_name(uid_t uid)
{
    struct passwd *pwd;
    static char user_id[10];

    if((pwd = getpwuid(uid)) == NULL)
    {
        sprintf(user_id, "%d", uid);
        return user_id;
    }
    else
        return pwd->pw_name;
}

char * gid_to_name(gid_t gid)
{
    struct group *group;
    static char group_id[10];

    if((group = getgrgid(gid)) == NULL)
    {
        sprintf(group_id, "%d", gid);
        return group_id;
    }
    else
        return group->gr_name;
}

void transfer_mode(mode_t mode, char mode_str[])
{
    strcpy(mode_str, "----------");

    if(S_ISDIR(mode))   mode_str[0] = ‘d‘;
    if(S_ISCHR(mode))   mode_str[0] = ‘c‘;
    if(S_ISBLK(mode))   mode_str[0] = ‘b‘;
    if(S_ISLNK(mode))   mode_str[0] = ‘l‘;
    if(S_ISFIFO(mode))   mode_str[0] = ‘p‘;
    if(S_ISSOCK(mode))   mode_str[0] = ‘s‘;

    if(mode & S_IRUSR)  mode_str[1] = ‘r‘;
    if(mode & S_IWUSR)  mode_str[2] = ‘w‘;
    if(mode & S_IXUSR)  mode_str[3] = ‘x‘;

    if(mode & S_IRGRP)  mode_str[4] = ‘r‘;
    if(mode & S_IWGRP)  mode_str[5] = ‘w‘;
    if(mode & S_IXGRP)  mode_str[6] = ‘x‘;

    if(mode & S_IROTH)  mode_str[7] = ‘r‘;
    if(mode & S_IWOTH)  mode_str[8] = ‘w‘;
    if(mode & S_IXOTH)  mode_str[9] = ‘x‘;
}





linux编程实践4(实现ls -l命令)

上一篇:Cocos2d-x中动画速度控制


下一篇:echo 命令