实现stat命令

来源:互联网 发布:python3写网络爬虫 编辑:程序博客网 时间:2024/04/30 09:22
#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <time.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <pwd.h>#include <grp.h>int main(int argc,char* argv[]){if(argc<2){printf("./mystat filename\n");exit(1);}// 文件信息结构体struct stat st;int ret = stat(argv[1],&st);if(ret == -1){perror("stat");exit(1);}//存储文件类型和访问权限char perms[11] = { 0 };//判断文件类型switch(st.st_mode & S_IFMT){case S_IFLNK:perms[0] = 'l';break;case S_IFDIR:perms[0] = 'd';break;case S_IFREG:perms[0] = '-';break;case S_IFBLK:perms[0] = 'b';break;case S_IFSOCK:perms[0] = 's';break;case S_IFIFO:perms[0] = 'f';break;default:perms[0] = '?';break;}//判断文件的访问属性//文件所有者perms[1] = (st.st_mode & S_IRUSR) ? 'r':'-';perms[2] = (st.st_mode & S_IWUSR) ? 'w':'-';perms[3] = (st.st_mode & S_IXUSR) ? 'x':'-';//判断所有组perms[4] = (st.st_mode & S_IRGRP) ? 'r':'-';perms[5] = (st.st_mode & S_IWGRP) ? 'w':'-';perms[6] = (st.st_mode & S_IXGRP) ? 'x':'-';//判断其他人perms[7] = (st.st_mode & S_IROTH) ? 'r':'-';perms[8] = (st.st_mode & S_IWOTH) ? 'w':'-';perms[9] = (st.st_mode & S_IXOTH) ? 'x':'-';//硬链接计数int linkNum = st.st_nlink;//文件所有者char* fileUser = getpwuid(st.st_uid)->pw_name;//文件所属组char* fileGrp = getgrgid(st.st_gid)->gr_name;//文件大小int fileSize = st.st_size;//修改时间char* time = ctime(&st.st_mtime);char mtime[512] = {0};strncpy(mtime,time,strlen(time)-1);char buf[1024];sprintf(buf,"%s %d %s %s %d %s %s %s",perms,linkNum,fileUser,fileGrp,fileSize,mtime,argv[1]);printf("%s\n",buf);return 0;}