ls (options) (参数)
1、options即为选项,常见的选项有如下…
-a:显示所有档案及目录(ls内定将档案名或目录名称为“.”的视为影藏,不会列出);
-A:显示除影藏文件“.”和“..”以外的所有文件列表;
-F:在每个输出项后追加文件的类型标识符,具体含义:“*”表示具有可执行权限的普通文件,“/”表示目录,“@”表示符号链接,“|”表示命令管道FIFO,“=”表示sockets套接字。当文件为普通文件时,不输出任何标识符;
-b:将文件中的不可输出的字符以反斜线“”加字符编码的方式输出;
-f:此参数的效果和同时指定“aU”参数相同,并关闭“lst”参数的效果;
-k:以KB(千字节)为单位显示文件大小;
-l:以长格式显示目录下的内容列表。输出的信息从左到右依次包括文件名,文件类型、权限模式、硬连接数、所有者、组、文件大小和文件的最后修改时间等;
-r:以文件名反序排列并输出目录内容列表;
-s:显示文件和目录的大小,以区块为单位;
-t:用文件和目录的更改时间排序;
-L:如果遇到性质为符号链接的文件或目录,直接列出该链接所指向的原始文件或目录;
-R:递归处理,将指定目录下的所有文件及子目录一并处理;
注:选项可以多个进行组合使用,具体可实践查看效果。
2、参数
参数为要显示的路径或文件,如不指定则为当前路径。
3、代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <time.h>
//获取类型
void f_type(const struct stat *s)
{
switch(s->st_mode & S_IFMT)
{
case S_IFSOCK: printf("s");break;
case S_IFLNK: printf("l");break;
case S_IFREG: printf("-");break;
case S_IFBLK: printf("b");break;
case S_IFDIR: printf("d");break;
case S_IFCHR: printf("c");break;
case S_IFIFO: printf("p");break;
}
}
//获取权限
void f_mode(const struct stat* s)
{
printf("%c",s->st_mode&S_IRUSR ? 'r':'-');
printf("%c",s->st_mode&S_IWUSR ? 'w':'-');
printf("%c",s->st_mode&S_IXUSR ? 'x':'-');
printf("%c",s->st_mode&S_IRGRP ? 'r':'-');
printf("%c",s->st_mode&S_IWGRP ? 'w':'-');
printf("%c",s->st_mode&S_IXGRP ? 'x':'-');
printf("%c",s->st_mode&S_IROTH ? 'r':'-');
printf("%c",s->st_mode&S_IWOTH ? 'w':'-');
printf("%c",s->st_mode&S_IXOTH ? 'x':'-');
}
//计算目录文件层数
int dir_level(const char *path)
{
int count=0;
DIR* dir=opendir(path);
if(NULL==dir) return -1;
for(struct dirent* d=readdir(dir);d!=NULL;d=readdir(dir))
{
count+=(d->d_type==DT_DIR);
}
closedir(dir);
dir=NULL;
return count;
}
//获取属主/属组名
void f_list(const struct stat* s)
{
struct passwd* name=NULL;
name=getpwuid(s->st_uid);
printf(" %s",name->pw_name);
name=getpwuid(s->st_gid);
printf(" %s",name->pw_name);
}
//获取文件所占字节数
void f_size(const struct stat* s)
{
printf(" %4ld",s->st_size);
}
//获取文件时间
void f_time(const struct stat* s)
{
time_t time=s->st_mtim.tv_sec;
struct tm *t=localtime(&time);
printf(" %2d月",t->tm_mon+1);
printf(" %2d",t->tm_mday);
printf(" %2d:%2d",t->tm_hour,t->tm_min);
}
//获取文件名
void f_name(const struct stat* s)
{
}
//对文件path进行ls -al
void list_file_stat(const char *path)
{
//获取文件属性
struct stat buf;
if(stat(path,&buf))
{
perror("stat");
return;
}
f_type(&buf);
f_mode(&buf);
printf(" %2d",S_ISDIR(buf.st_mode)? dir_level(path):1);
f_list(&buf);
f_size(&buf);
f_time(&buf);
}
int main(int argc,const char* argv[])
{
DIR* dir=NULL;
if(argc==1)
dir=opendir(".");
else
{
dir=opendir(argv[1]);
//更改当前工作路径
chdir(argv[1]);
}
for(struct dirent* d=readdir(dir);d!=NULL;d=readdir(dir))
{
list_file_stat(d->d_name);
printf(" %s\n",d->d_name);
}
return 0;
}
4、运行结果如下:

系统指令ls -al:

1259

被折叠的 条评论
为什么被折叠?



