Linux基础?ls功能的简单实现
作者:网络转载 发布时间:[ 2014/10/13 10:23:02 ] 推荐标签:操作系统 Linux
简单的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中。

sales@spasvo.com