#include <stdio.h>
#include <string.h>
#include <pwd.h>//用户信息
#include <sys/types.h>
#include <time.h>//时间
#include <sys/stat.h>//文件信息
#include <sys/sysmacros.h>
#include <grp.h>//用户所在组
#include <dirent.h> //目录
#include <unistd.h>
int main (int argc, char *argv[]){
if(argc != 2){
argv [1] = "./";
}
DIR *dirp = opendir (argv [1]);
if (dirp ==NULL){
perror("opendir");
return -1;
}
struct dirent *dirent = NULL;
struct stat mybuf;
int total = 0;//总用量块数
while(1){
dirent = readdir(dirp);
if (dirent == NULL)
break;
if(strncmp(".",dirent->d_name,1)==0)
continue;
stat(dirent->d_name,&mybuf);
if(S_ISREG(mybuf.st_mode)) {
//常规设备
printf ( "-");
}else if(S_ISCHR(mybuf.st_mode)) {
//字符设备实验未成功
printf ("c") ;
//主设备号次设备号
printf ("%d %d ",major(mybuf.st_rdev),minor(mybuf.st_rdev));
}else if(S_ISDIR(mybuf.st_mode)){
printf ("d");//目录实验成功
}
#ifdef S_ISLNK
else if(S_ISLNK(mybuf.st_mode)){
//符号连接,当打开一个符号链接,直接访问了源文件,实验失败
printf ("l");
}
#endif
//文件权限
printf ("%c",mybuf.st_mode &(0x1<<8)?'r':'-');
printf ("%c",mybuf.st_mode &(0x1<<7)?'w':'-');
printf ("%c",mybuf.st_mode &(0x1<<6)?'x':'-');
printf ("%c",mybuf.st_mode &(0x1<<5)?'x':'-');
printf ("%c",mybuf.st_mode &(0x1<<4)?'w':'-');
printf ("%c",mybuf.st_mode &(0x1<<3)?'x':'-');
printf ("%c",mybuf.st_mode &(0x1<<2)?'r':'-');
printf ("%c",mybuf.st_mode &(0x1<<1)?'w':'-');
printf ("%c",mybuf.st_mode &(0x1<<0)?'x':'-');
//连接数
printf ("%ld",mybuf.st_nlink);
//用户
struct passwd *p = getpwuid(mybuf.st_uid);
printf ("%s",p->pw_name);
//所在组
struct group *g = getgrgid(mybuf.st_gid);
printf ("%s",g->gr_name);
//文件大小
printf("%6ld",mybuf.st_size);
//最后一次修改时间
struct tm *k = localtime(&mybuf.st_mtime);
printf ("%d月 ",k->tm_mon+1);
printf ("%2d ",k->tm_mday);
printf ("%d:%d ",k->tm_hour,k->tm_min);
//文件名
printf ("%s ",dirent->d_name);
printf ("\n");
//块数
total += mybuf.st_blocks/2;
}
printf("总用量:%d\n", total);
closedir(dirp);
return 0;
}
使用头文件#include <unistd.h>含有的常量与函数复写ls -l命令
最新推荐文章于 2023-02-05 21:44:10 发布