暑假留校前两天
实现ls命令基础功能:
主要问题:
一些玄学问题(改了好久 )
当使用lstat(path,&buf)函数时,如果path路径最后含有 / 符号(例home/),函数无法正常使用。
此处有问题,需要先用一个int数据接一下(图一strcat()下面一行,图二int xxx),不能直接操作。
因为电脑原因,无法完整实现ls -R类全部功能(某些Windows文件无法访问)
- 拓展知识
- 当我在写总用量的时候,在鸟哥里面,我知道了在linux文件系统中,与目录相关的权限和属性等信息是存放在inode中, 目录中的文件名都存放在最小存储单位data block中, 默认为4k也就是4096,但是实际上,并不是所有的文件都能占到4k,所以当目录中的文件容量少于4096时,用ls -l命令就会看到目录的大小是4096,. 当文件的数量大于4096小于8192时, 用ls -l命令就会看到目录的大小是8192, 以此类推。
linux系统中的单个文件的权限和属性等信息是存放在inode中的, 文件的内容是存放在data block中, 跟目录类似, 如果文件的内容大小不足4096个字节, 也会占用一个data block. 因此用ls -l命令查看文件的大小却不是4096的倍数。
所以这就牵扯出,你所看到的单个文件占用容量相加并不是他所占有的有效容量。
// 代码
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <linux/limits.h>
#define PARAM_NONE 0
#define PARAM_A 1
#define PARAM_L 2
#define PARAM_R 4
#define MAXROWLEN 150
int g_leave_len = MAXROWLEN;
int g_maxlen; //存放某目录下最长文件名的长度
int clour; //底色
unsigned long long sum;
void my_err(char error[],int num){
fprintf(stderr,"line :%d",num);
perror(error);
exit(1);
}
void getclour(char name[]){
struct stat buf;
lstat(name,&buf);
if(S_ISREG(buf.st_mode)){
clour = 37;
if((buf.st_mode&S_IXOTH)||(buf.st_mode&S_IXGRP)||(buf.st_mode&S_IXUSR)){
clour = 32;
}
}
else if(S_ISDIR(buf.st_mode)){
clour = 34;
}
else if(S_ISCHR(buf.st_mode)){
clour = 33;
}
else if(S_ISBLK(buf.st_mode)){
clour = 33;
}
else if(S_ISFIFO(buf.st_mode)){
clour = 35;
}
else if(S_ISLNK(buf.st_mode)){
clour = 36;
}
else if(S_ISSOCK(buf.st_mode)){
clour = 36;
}
}
void display_attribute(struct stat buf,char * name)
{
char buf_time[32];
struct passwd *psd;
struct group *grp;
getclour(name);
if(S_ISREG(buf.st_mode)){
printf("-");
}
else if(S_ISDIR(buf.st_mode)){
printf("d");
}
else if(S_ISCHR(buf.st_mode)){
printf("c");
}
else if(S_ISBLK(buf.st_mode)){
printf("b");
}
else if(S_ISFIFO(buf.st_mode)){
printf("f");
}
else if(S_ISLNK(buf.st_mode)){
printf("l");
}
else if(S_ISSOCK(buf.st_mode)){
printf("s");
}
if(buf.st_mode & S_IRUSR){
//用户的权限
printf("r");
}else
printf(