今日任务
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <dirent.h>
#include <grp.h>
#include <time.h>/** function: 打印某个文件的基本属性:* @param [ in] * @param [out] * @return */
int print_file_info(char *filename){//定义结构体变量接受文件的属性struct stat buf;//printf("---%s---\n",filename);if(-1==stat(filename,&buf)){perror("stat");printf("%d",__LINE__);return -1;}//打印文件类型switch (buf.st_mode & S_IFMT) {case S_IFBLK: printf("b"); break;case S_IFCHR: printf("c"); break;case S_IFDIR: printf("d"); break;case S_IFIFO: printf("p"); break;case S_IFLNK: printf("l"); break;case S_IFREG: printf("-"); break;case S_IFSOCK: printf("s"); break;default: printf("?"); break;}//打印文件权限for (int i=0; i<9; i++){if(0==(buf.st_mode & 0400>>i)){putchar('-');}else{if(i%3==0)putchar('r');else if(i%3==1)putchar('w');else if(i%3==2)putchar('x');elseputchar('?');}}//打印文件硬链接个数printf(" %ld ",buf.st_nlink);//打印用户名struct passwd* pwd=getpwuid(buf.st_uid);if(NULL==pwd){perror("getpwuid");printf("%d",__LINE__);return -1;}printf("%s ",pwd->pw_name);//打印用户所在组名struct group* grp=getgrgid(buf.st_gid);if(NULL==grp){perror("getgrgid");printf("%d",__LINE__);return -1;}printf("%s ",grp->gr_name);//打印文件大小printf("%5ld ",buf.st_size);//打印时间struct tm *time=localtime(&buf.st_atime);printf("%4d %d %d:%d ",time->tm_mon+1,time->tm_mday,time->tm_hour,time->tm_min);//打印文件名printf(" %s\n ",filename);return 0;
}
/** function: 打印某个目录下的所有文件名()* @param [ in] * @param [out] * @return */
int print_all_file(char *filepath){DIR * od=opendir(filepath);if(NULL==od){perror("opendir");printf("%d",__LINE__);return -1;}//读取文件,循环打印文件名struct dirent* rd=NULL;while(1){rd=readdir(od);if(NULL==rd)break;if('.'==rd->d_name[0])continue;char file[20]="";strcpy(file,filepath);//strcat(file,"/");strcat(file,rd->d_name);//printf("%s\n",file);print_file_info(file);}closedir(od);return 0;
}
int main(int argc, const char *argv[])
{puts("please input directory name you want to printf");char filepath[20]="";scanf("%s",filepath);print_all_file(filepath);//print_file_info("1.txt");return 0;
}
运行结果:
今日思维导图: