您的位置:首页 > 编程语言 > C语言/C++

C语言实现ls -l 命令(2)

2018-01-29 11:29 429 查看
欢迎加入QQ:498903810 一起交流、讨论知识,里面有大佬,也有小白,天下码农一家亲,大家一起讨论进步。

相关函数请参考本博客的
linux下的文件操作
文章


linux下的文件操作url:连接地址

博客主页url:连接地址

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <pwd.h>
#include <time.h>
#include <grp.h>

void func1(struct stat * p)
{
switch(p->st_mode & S_IFMT)
{
case S_IFSOCK:printf("s");break;
case S_IFLNK:printf("l");break;
case S_IFBLK:printf("b");break;
case S_IFDIR:printf("d");break;
default:printf("-");
}

/*
if(S_ISLNK(p->st_mode))//是否是链接
printf("l");
else if(S_ISREG(p->st_mode))//普通文件
printf("-");
else if(S_ISDIR(p->st_mode))//文件夹
printf("d");
else if(S_ISCHR(p->st_mode))//字符设备
printf("c");
else if(S_ISCHR(p->st_mode))//block设备
printf("b");
else if(S_ISFIFO(p->st_mode))//FIFO文件
printf("f");
else if(S_ISSOCK(p->st_mode))//socket
printf("s");
else
printf("-");
*/
}
void func2(struct stat * p)
{
//所有者的权限
if(p->st_mode & S_IRWXU &  S_IRUSR)
printf("r");
else
printf("-");
if(p->st_mode & S_IRWXU & S_IWUSR)
printf("w");
else
printf("-");
if(p->st_mode & S_IRWXU & S_IXUSR)
printf("x");
else
print
a598
f("-");

//所属组的权限
if(p->st_mode & S_IRWXG & S_IRGRP)
printf("r");
else
printf("-");
if(p->st_mode & S_IRWXG & S_IWGRP)
printf("w");
else
printf("-");
if(p->st_mode & S_IRWXG & S_IXGRP)
printf("x");
else
printf("-");

//其他人的权限
if(p->st_mode & S_IRWXO & S_IROTH)
printf("r");
else
printf("-");
if(p->st_mode & S_IRWXO & S_IWOTH)
printf("w");
else
printf("-");
if(p->st_mode & S_IRWXO & S_IXOTH)
printf("x.");
else
printf("-.");
}
void func3(char * tmp)
{
//Sun Jan 28 15:51:39 2018
int i = 0;
int j = 0;
char sign[64];

for(i = 4, j = 0; i < 16; i++, j++)
{
sign[j] = tmp[i];
}
sign[j] = '\0';
printf(" %s", sign);
}

int main()
{
char * p_time = NULL;
DIR * p_dir = NULL;
long int second = 0;
struct tm t;
struct stat st;
struct dirent *p = NULL;
struct passwd *p_uid = NULL;
struct group *p_gid = NULL;

p_dir = opendir(".");
p = readdir(p_dir);

while(p)
{
lstat(p->d_name, &st);
if(*p->d_name == '.')
{
p = readdir(p_dir);//打开下一个文件
stat(p->d_name, &st);
continue;
}

func1(&st);//查看文件类型
func2(&st);//查看文件权限
printf("%3d ",st.st_nlink);//连接数

//获取用户名
p_uid = getpwuid(st.st_uid);
printf("%5s", p_uid->pw_name);

//获取组的名字
p_gid = getgrgid(st.st_gid);
printf("%6s", p_gid->gr_name);

printf("%6d", st.st_size);//查看文件大小

p_time = ctime(&(st.st_mtime));//打印日期
func3(p_time);

printf(" %s", p->d_name);//打印文件名

p = readdir(p_dir);//打开下一个文件
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: