设为首页 收藏本站
查看: 1033|回复: 2

[经验分享] linux系统编程之文件与IO:实现ls -l功能

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2013-7-12 09:10:13 | 显示全部楼层 |阅读模式

本文利用以下系统调用实现ls -l命令的功能:


1,lstat:获得文件状态,

2,getpwuid:

#include <pwd.h>

struct passwd *getpwuid(uid_t uid);

描述:

The getpwuid() function returns a pointer to a structure containing the broken-out fields of the record in the password database  that  matches the user ID uid.

返回值:
The passwd structure is defined in <pwd.h> as follows:

    struct passwd {
        char   *pw_name;       /* username */
        char   *pw_passwd;     /* user password */
        uid_t   pw_uid;        /* user ID */
        gid_t   pw_gid;        /* group ID */
        char   *pw_gecos;      /* real name */
        char   *pw_dir;        /* home directory */
        char   *pw_shell;      /* shell program */
    };

示例:

#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <pwd.h>#define ERR_EXIT(m) \    do \    { \        perror(m); \        exit(EXIT_FAILURE); \    } while(0)int main(void){    uid_t uid;    struct passwd *pw;    uid = getuid();    printf("current user id :%d\n",uid);    if((pw = getpwuid(uid)) == NULL)        ERR_EXIT("getpwuid error");    printf("username:%s\n",pw->pw_name);    printf("user passwd:%s\n",pw->pw_passwd);    printf("user ID:%d\n",pw->pw_uid);    printf("group ID:%d\n",pw->pw_gid);    //printf("real name:%s\n",pw->pw_gecos);    printf("home directory:%s\n",pw->pw_dir);    printf("shell program:%s\n",pw->pw_shell);    return 0;}

运行结果:

7547481_1373552996GSdO.jpg

3,getgrgid:

#include <grp.h>

struct group *getgrnam(const char *name);//根据组名获得组信息

struct group *getgrgid(gid_t gid);//根据组ID获得组信息

描述:

The getgrnam() function returns a pointer to a structure containing the broken-out  fields of the record in the group database (e.g., the local group file /etc/group, NIS, and LDAP) that matches the group name name.

The getgrgid() function returns a pointer to a structure containing the broken-out fields of the record in the group database that matches  thegroup ID gid.

返回值:

The group structure is defined in <grp.h> as follows:

    struct group {
        char   *gr_name;       /* group name */
        char   *gr_passwd;     /* group password */
        gid_t   gr_gid;        /* group ID */
        char  **gr_mem;        /* group members */
    };


4,readlink:读取软链接文件的内容

#include <unistd.h>

ssize_t readlink(const char *path, char *buf, size_t bufsiz);

描述:

DESCRIPTION
       readlink() places the contents of the symbolic link path in the  buffer
       buf,  which has size bufsiz.  readlink() does not append a null byte to
       buf.  It will truncate the contents (to a length of bufsiz characters),
       in case the buffer is too small to hold all of the contents.

RETURN VALUE
       On  success,  readlink() returns the number of bytes placed in buf.  On
       error, -1 is returned and errno is set to indicate the error.

示例:

#include <unistd.h>#include <stdlib.h>#include <stdio.h>#define ERR_EXIT(m) \    do \    { \        perror(m); \        exit(EXIT_FAILURE); \    } while(0)int main(int argc,char **argv){    if(argc != 2){        fprintf(stderr,"usage:%s linkfile", argv[0]);        exit(EXIT_FAILURE);    }    char buf[1024];        if(readlink(argv[1],buf,1024) ==-1)        ERR_EXIT("readlink error");    printf("the content of %s are: %s\n",argv[1],buf);    return 0;}

运行结果:

7547481_1373552997I4WU.jpg

现在利用相关的系统调用实现ls –l功能:

程序如下:

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <dirent.h>#include <sys/types.h>#include <sys/stat.h>#include <string.h>#include <time.h>#include <pwd.h> #include <grp.h> #include <libgen.h>#define ERR_EXIT(m) \    do\    {\        perror(m);\        exit(EXIT_FAILURE);\    }while(0)\void lsdir(char *dirname);void lsfile(char *filename);void lsfile(char *filename);char getFileType(struct stat *fstat);void getFilePerm(struct stat *st, char *perm);int main(int argc,char **argv){    if(argc != 2){        fprintf(stderr,"usage:%s [filepath]\n",argv[0]);        exit(EXIT_FAILURE);    }    struct stat fstat;    if(lstat(argv[1],&fstat) == -1)        ERR_EXIT("STAT ERROR");    if(S_ISDIR(fstat.st_mode))    {        lsdir(argv[1]);    }    else{        lsfile(argv[1]);    }    return 0;}void lsdir(char *dirname){    DIR *dir;    char filename[100] = {0};    dir =opendir(dirname);     if(dir == NULL)        ERR_EXIT("opendir error");    struct dirent *dentry;    while((dentry = readdir(dir)) != NULL)    {                char *fname;        fname = dentry->d_name;        if(strncmp(fname,".",1) == 0)            continue;        sprintf(filename,"%s/%s",dirname,fname);        lsfile(filename);    }    closedir(dir);}//-rw-r--r--.   1            zxy        zxy        2586        Jul 10 17:00    ls.c//类型及权限  硬链接数        拥有者    所属组    文件大小    创建时间        文件名void lsfile(char *filename){    struct stat tmpstat;    if(lstat(filename,&tmpstat) == -1)        ERR_EXIT("STAT ERROR");    char buf[11]= {0};    strcpy(buf,"----------");    char type;    type = getFileType(&tmpstat);    char *bname = basename(filename);    buf[0] = type;    if(type == 'l'){        char content[1024];        if(readlink(filename,content,1024) == -1)            ERR_EXIT("readlink error");        sprintf(bname,"%s -> %s",bname,content);    }    getFilePerm(&tmpstat,buf);    struct tm *ftime;    ftime = localtime(&tmpstat.st_mtime);        printf("%s %d %s %s %10ld %02d %02d %02d:%02d %s\n",        buf,tmpstat.st_nlink,        getpwuid(tmpstat.st_uid)->pw_name,        getgrgid(tmpstat.st_gid)->gr_name,        tmpstat.st_size,        ftime->tm_mon+1,        ftime->tm_mday,        ftime->tm_hour,        ftime->tm_min,        bname);}//获得文件类型char getFileType(struct stat *st){    char type = '-';    switch (st->st_mode  & S_IFMT)    {        case S_IFSOCK:        type = 's';                break;        case S_IFLNK:        type = 'l';                break;        case S_IFREG:        type = '-';                break;        case S_IFBLK:        type = 'b';                break;        case S_IFDIR:        type = 'd';                break;        case S_IFCHR:        type = 'c';                break;        case S_IFIFO:        type = 'p';                break;    }    return type;}//获得文件访问权限void getFilePerm(struct stat *st, char *perm){    mode_t mode = st->st_mode;    if (mode & S_IRUSR)        perm[1] = 'r';    if (mode & S_IWUSR)        perm[2] = 'w';    if (mode & S_IXUSR)        perm[3] = 'x';    if (mode & S_IRGRP)        perm[4] = 'r';    if (mode & S_IWGRP)        perm[5] = 'w';    if (mode & S_IXGRP)        perm[6] = 'x';    if (mode & S_IROTH)        perm[7] = 'r';    if (mode & S_IWOTH)        perm[8] = 'w';    if (mode & S_IXOTH)        perm[9] = 'x';}


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.iyunv.com/thread-7417-1-1.html 上篇帖子: linux系统编程之文件与IO:stat()系统调用获取文件信息 下篇帖子: linux系统编程之文件与I0:文件描述符相关操作-dup,dup2,fcntl linux

尚未签到

发表于 2013-9-23 08:10:30 | 显示全部楼层
打破老婆终身制,实行小姨股份制。引入小姐竞争制,推广情人合同制。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

尚未签到

发表于 2014-1-5 11:27:53 | 显示全部楼层
说是不要迷恋伱 可我从来麽爱过妳

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表