一个类ls函数
2016-02-14 19:55
316 查看
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <string.h> #include <pwd.h> #include <time.h> #include <grp.h> void showls(struct stat *p,char * d_name) { char flag; if(S_ISREG(p->st_mode))flag='-'; else if(S_ISDIR(p->st_mode))flag='d'; else if(S_ISCHR(p->st_mode))flag='c'; else if(S_ISBLK(p->st_mode))flag='b'; else if(S_ISSOCK(p->st_mode))flag='s'; else if(S_ISFIFO(p->st_mode))flag='P'; else if(S_ISLNK(p->st_mode))flag='l'; else flag='?'; printf("%c\t",flag); //printf("%o\t",p->st_mode&0777); const char* rwx="rwx"; int i; for(i=0;i<9;i++) printf("%c",p->st_mode&0400?rwx[i%3]:'-'); printf("\t"); printf("%2ld\t",p->st_nlink); struct passwd *s; s=getpwuid(p->st_uid); printf("%7s\t",s->pw_name); printf("%7s\t",getgrgid(p->st_gid)->gr_name); printf("%ld\t",p->st_size); char buf[100]; time_t t=p->st_mtime; strftime(buf,sizeof(buf),"%F %T",localtime(&t)); printf("%s\t",buf); printf("%s\t",d_name); printf("\n"); } int main(int argc,char* argv[]) { char* path; if(argc==1) { path="."; } if(argc==2&&strcmp(argv[1],"-l")==0) { path="."; } else if(argc==2) { path=argv[1]; } if(argc==3) { path=argv[2]; } if(argc>=2&&strcmp(argv[1],"-l")==0) printf("类型\t权限\t\t链接数\t用户名\t组\t字节数\t最后一次修改时间\t文件名\n"); if(opendir(path)==NULL) {//检查是否有这个目录 printf("文件打开失败!请正确输入!\n"); printf("%m"); return -1; } DIR *p = opendir(path);//指针指向当前路径的所有内容 if(chdir(path)!=0) {//设置 path 作为当前工作目录 perror("错误"); return -1; } struct dirent *q;//结构体划分内容块 while((q=readdir(p))!=NULL) {//从工作目录读取 if(q->d_name[0]=='.') continue;//不显示隐藏文件 if(argc>=2&&strcmp(argv[1],"-l")==0) { struct stat s; stat(q->d_name,&s); showls(&s,q->d_name); } if(argc==1) printf("%s\t",q->d_name); } printf("\n"); closedir(p); return 0; }
相关文章推荐
- 《Linux常用命令第一关(2)》
- spring 方法注入
- 堆排序
- 2016年,不在做一个只说不做的人,落实行动,从今天开始
- iOS 文件操作:沙盒(SandBox)、文件操作(FileManager)、程序包(NSBundle)
- [BZOJ2794][Poi2012]Cloakroom
- Linux介绍(二)
- ios相对路径与绝对路径的转化NSBundle
- 回文串和镜像串(摘)
- Adafruit的樹莓派教程第十三課:電力控制
- Java基础——I/O续
- Mysql 使用分区
- ViewPager标签栏滑条
- Swift开发笔记-Mac OS X 天气预报应用开发(Xcode7.2)
- Material-design icon生成插件
- Adafruit的樹莓派教程第十二課:感知運動
- 【设计模式】4、原型模式
- centos 7 yum源配置
- [C++]在cout時自動補零 【格式化输出】
- POJ1837 动态规划 天平问题