Linux系统下,对ls -l命令的代码实现
就剩文件的颜色没弄好,基本的功能已经实现了
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "list_wan.h" //自己写的一个链表
//$blue = -e "\033[1;32mHello Linux\033[0m"
typedef struct Node
{
char arr[100];
char name[20];
}Node;
void get_stat(const char* name,Node* node)
{
struct stat sta;
stat(name,&sta);
mode_t m = sta.st_mode;
strcat(node->arr,S_IRUSR&m?"r":"-");
strcat(node->arr,S_IWUSR&m?"w":"-");
strcat(node->arr,S_IXUSR&m?"x":"-");
strcat(node->arr,S_IRGRP&m?"r":"-");
strcat(node->arr,S_IWGRP&m?"w":"-");
strcat(node->arr,S_IXGRP&m?"x":"-");
strcat(node->arr,S_IROTH&m?"r":"-");
strcat(node->arr,S_IWOTH&m?"w":"-");
strcat(node->arr,S_IXOTH&m?"x":"-");
if(S_ISDIR(m))
{
int flag = 2;
DIR* fl = opendir(name);
for(struct dirent* dir = readdir(fl); NULL!=dir;)
{
if(dir->d_type==DT_DIR && dir->d_name[0]!='.')
{
flag++;
}
dir = readdir(fl);
}
char arr[5]={};
sprintf(arr," %d",flag);
strcat(node->arr,arr);
closedir(fl);
}
else
{
strcat(node->arr," 1");
}
char arr[30]={};
struct passwd* pas = getpwuid(sta.st_uid);
sprintf(arr," %s",pas->pw_name);
strcat(node->arr,arr);
struct group* gro = getgrgid(sta.st_gid);
sprintf(arr," %s",gro->gr_name);
strcat(node->arr,arr);
sprintf(arr," %5ld",sta.st_size);
strcat(node->arr,arr);
struct tm* temp = localtime(&sta.st_mtime);
sprintf(arr," %2d月 %2d %02d:%02d ",temp->tm_mon+1,temp->tm_mday,temp->tm_hour,temp->tm_min);
strcat(node->arr,arr);
}
void get_dir(struct dirent* dir,List* list)
{
if(dir->d_name[0] == '.') return;
Node* node = malloc(sizeof(Node));
switch(dir->d_type)
{
case DT_BLK:
sprintf(node->arr,"%s","b");break;
case DT_CHR:
sprintf(node->arr,"%s","c");break;
case DT_DIR:
sprintf(node->arr,"%s","d");break;
case DT_FIFO:
sprintf(node->arr,"%s","q");break;
case DT_LNK:
sprintf(node->arr,"%s","l");break;
case DT_REG:
sprintf(node->arr,"%s","-");break;
case DT_SOCK:
sprintf(node->arr,"%s","s");break;
case DT_UNKNOWN:
sprintf(node->arr,"%s","?");break;
}
get_stat(dir->d_name,node);
sprintf(node->name,"%s",dir->d_name);
add_tail_list(list,node);
}
int main(int argc,char *argv[])
{
List* list = create_list();
if(argc != 2 || strcmp("-l",argv[1]))
{
printf("User:./ls -l\n");
return -1;
}
int temp = open("./",O_RDONLY);
if(0 > temp)
{
perror("open");
return -1;
}
DIR *fl = fdopendir(temp);
for(struct dirent *dir=readdir(fl); NULL!=dir;)
{
get_dir(dir,list);
dir = readdir(fl);
}
closedir(fl);
int cmp(const void* ptr1,const void* ptr2)
{
const Node* node1 = ptr1;
const Node* node2 = ptr2;
return strcmp(node1->name,node2->name);
}
sort_list(list,cmp);
void show(const void* ptr)
{
const Node* node = ptr;
printf("%s",node->arr);
// system("echo blue");
printf("%s\n",node->name);
}
show_list(list,show);
}