Linux基础—ls功能的简单实现

发表于:2014-10-13 10:42

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:(@_@)ゞ    来源:51Testing软件测试网采编

  简单的ls实现,首先,我们需要遍历参数目录下的各个文件,再根据文件相应的性质,读取文件的权限,用户组,用户名,大小,最后一次访问的时间,再根据文件名排序后依次显示。
  具体的函数声明如下:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <dirent.h>
8 #include <sys/types.h>
9 #include <pwd.h>
10 #include <grp.h>
11 #include <time.h>
12 #define CNT 256
13 int file_name(DIR *fp, char *path, char name[][CNT]);
14 void str_sort(char name[][CNT], int cnt);
15 void mode_to_char(mode_t mode, char *buf);
16 char *time_change(char *time);
17 void show(char name[][CNT], int cnt);
  目录的遍历,我们需要知道目录下读取到的文件个数,所以需要返回相应的int型值。
  目录的遍历实现如下:
1intfile_name(DIR*fp,char*path,charname[][CNT])
2{
3intcnt=0;
4structdirent*p;
5while((p=readdir(fp))!=NULL)
6{
7if(strncmp(p->d_name,".",1)==0||strncmp(p->d_name,"..",2)==0)
8continue;
9strcpy(name[cnt],path);
10strcat(name[cnt],"/");
11strcat(name[cnt],p->d_name);
12cnt++;
13}
14closedir(fp);
15returncnt;
16}
  然后我们需要了解文件的权限,文件权限保存在相对应的参数char *buf中。
31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号