資源簡(jiǎn)介
這是自己寫的ls -R函數(shù),實(shí)現(xiàn)了分欄、隱藏文件隱藏、上色等功能,沒有排序。用的時(shí)候根據(jù)輸入不同有兩種功能 ls 和ls -R 、用的時(shí)候只要再加一個(gè)主函數(shù)就可以了。
代碼片段和文件信息
#include
#include
#include
#include
#include
void?do_ls(char[]int);
void?dostat(char?*char?*);
void?show_file_info(?char?*?struct?stat?*);
void?mode_to_letters(?int??char?[]?);
char?*uid_to_name(?uid_t?);
char?*gid_to_name(?gid_t?);
lsR(int?ac?char?*av[])
{
int R_flag?=?0;
int anyfiles?=??0;
while?(?--ac?){
if?(?strcmp(“-R“?*++av)?==?0?)
R_flag?=?1;
else?{
do_ls(?*av??R_flag?);
anyfiles?=?1;
}
}
if?(?!anyfiles?)
do_ls(“.“?R_flag);
}
void?do_ls(?char?dirname[]??int?subdirs?)
{
DIR *dir_ptr;
struct?dirent *direntp;
char *fullpath;
if?(?(?dir_ptr?=?opendir(?dirname?)?)?==?NULL?){
fprintf(stderr“l(fā)s2:?cannot?open?%s\n“?dirname);
return;
}
printf(“%s:\n“?dirname);
fullpath?=?(char?*)malloc(strlen(dirname)?+?1?+?MAXNAMLEN?+?1);
while?(?(?direntp?=?readdir(?dir_ptr?)?)?!=?NULL??)
????{
???????????????char?cname[20];
???????????????strcpy(cnamedirentp->d_name);
???????????????if(cname[0]!=‘.‘)
????????{
sprintf(fullpath“%s/%s“dirnamedirentp->d_name);
dostat(?fullpath?direntp->d_name?);
}
????}
if?(?subdirs?){
rewinddir(dir_ptr);
while?(?(?direntp?=?readdir(?dir_ptr?)?)?!=?NULL?){
???????????????????????????????if(direntp->d_name[0]==‘.‘)
continue;
sprintf(fullpath“%s/%s“dirnamedirentp->d_name);
if?(?isadir1(fullpath)?){
putchar(‘\n‘);
do_ls(?fullpath?subdirs?);
}
}
}
closedir(dir_ptr);
free(fullpath);
}
void?dostat(?char?*fullpath?char?*filename?)
{
struct?stat?info;
if?(?lstat(fullpath?&info)?==?-1?)
perror(filename);
else
show_file_info(filename?&info);
}
void?show_file_info(?char?*filename?struct?stat?*info_p?)
{
char *uid_to_name()?*ctime()?*gid_to_name()?*filemode();
void mode_to_letters();
????????char????modestr[11];
mode_to_letters(?info_p->st_mode?modestr?);
printf(?“%s“?????modestr?);
printf(?“%4d?“???(int)?info_p->st_nlink);
printf(?“%-8s?“??uid_to_name(info_p->st_uid)?);
printf(?“%-8s?“??gid_to_name(info_p->st_gid)?);
printf(?“%8ld?“??(long)info_p->st_size);
評(píng)論
共有 條評(píng)論