操作系统第4次实验报告:文件系统

  • 姓名:徐思婕
  • 学号:201821121004
  • 班级:计算1811

1. 编写程序

  • 在服务器上用Vim编写一个程序:实现Linux系统命令ls -lai的功能,给出源代码:
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <dirent.h>
 #include <string.h>
 #include <time.h>
 #include <grp.h>
 #include <pwd.h>

char mode[10];//声明一个存储权限的字符数组 void mode_info_my(mode_t st_mode,char *mode); void my_stat(char *p) { char *time; int t; struct stat st_p; if(stat(p,&st_p) == -1) printf("stat error\n"); mode_info_my(st_p.st_mode,mode); printf("%s",mode); printf(" %ld",(long)st_p.st_nlink); printf(" %s",getpwuid(st_p.st_uid)->pw_name); printf(" %s",getgrgid(st_p.st_gid)->gr_name); printf(" %ld",(long)st_p.st_size); time=ctime(&st_p.st_ctime); t=strlen(time); time[t-1]='\0'; printf(" %s",time); } //获取文件或者目录的权限信息 void mode_info_my(mode_t st_mode,char *mode) { if(S_ISREG(st_mode)) mode[0]='-'; if(S_ISDIR(st_mode)) mode[0]='d'; if(S_ISCHR(st_mode)) mode[0]='c'; if(S_ISBLK(st_mode)) mode[0]='b'; if(st_mode & S_IRUSR) mode[1]='r'; else mode[1]='-'; if(st_mode & S_IWUSR) mode[2]='w'; else mode[2]='-'; if(st_mode & S_IXUSR) mode[3]='x'; else mode[3]='-'; if(st_mode & S_IRGRP) mode[4]='r'; else mode[4]='-'; if(st_mode & S_IWGRP) mode[5]='w'; else mode[5]='-'; if(st_mode & S_IXGRP) mode[6]='x'; else mode[6]='-'; if(st_mode & S_IROTH) mode[7]='r'; else mode[7]='-'; if(st_mode & S_IWOTH) mode[8]='w'; else mode[8]='-'; if(st_mode & S_IXOTH) mode[9]='x'; else mode[9]='-'; } int main(int argc,char *argv[]) { struct stat st; struct dirent *dp; DIR *c; char p[256]; char *dir=NULL; if(argc == 1){ //命令行只有一个参数情况,默认显示当前路径信息 argv[1]="."; } if(argc>2){ printf("command error\n"); return 1; } if(stat(argv[1],&st) != 0){ printf("fail to get stat of file\n"); return -1; } mode_info_my(st.st_mode,mode); if(mode[0] == 'd'){ //路径为目录的相应操作 if((c=opendir(argv[1]))==NULL){ //判断路径是否存在 printf("path is empty\n"); return -1; } if(chdir(argv[1])!=-1){ //切换到所给路径 dir=getcwd(dir,0); } my_stat(dir); //输出目录信息 while((dp=readdir(c)) != NULL){ //遍历目录下的文件和目录,并输出其信息 strcpy(p,argv[1]); strcat(p,"/"); strcat(p,dp->d_name); //文件路径连接 my_stat(p); //打印信息 printf(" %s\n",dp->d_name);//输出文件名 } } else //参数是文件,输出文件信息 my_stat(argv[1]); return 0; }

 

2. 分析运行结果

  • 给出运行结果截图,对于每一列是如何获取的,结合源代码做解释:

         

          

  • 获取文件类型:(第一列)

        

  • 获取文件权限: (第一列)

         

  • 文件硬件连接数:(第二列)

         

  • 属主用户:(第三列)

         

  • 组用户:(第四列)

         

  • 文件所占用的大小:(第五列)

         

  • 最后修改时间:(第六列)

         

  • 文件名:(第七列)

         

 

posted @ 2020-04-30 16:24  一昼  阅读(237)  评论(0编辑  收藏  举报