# include <stdio.h>
# include <sys/types.h>
# include <dirent.h>
# include <sys/stat.h>
# include <unistd.h>
# include <time.h>
# include <string.h>
# include <pwd.h>
# include <grp.h>
void do_ls(char []);
void do_stat(char *);
void show_file_info(char *, struct stat *);
void mode_to_letters(int mode, char * modestr);
char * uid_to_name(uid_t);
char * gid_to_name(gid_t);
int main(int argc, char *argv[])
{
if(argc == 1)
do_ls(".");
else
while(--argc)
{
printf("%s:\n", *(++argv));
do_ls(*argv);
}
}
/*do ls the list files in directory*/
void do_ls(char dirname[])
{
DIR *dir_ptr;
struct dirent *dir_struct;
if((dir_ptr = opendir(dirname)) == NULL)
perror(dirname);
else
{
while((dir_struct = readdir(dir_ptr)) != NULL)
do_stat(dir_struct->d_name);
closedir(dir_ptr);
}
}
/*get the file information*/
void do_stat(char *filename)
{
struct stat info;
if(stat(filename, &info) == -1)
perror(filename);
else
show_file_info(filename, &info);
}
/*show the file information*/
void show_file_info(char *filename, struct stat *info_ptr)
{
char modestr[11];
mode_to_letters(info_ptr->st_mode, modestr);
printf("%s", modestr);
printf("%4d", info_ptr->st_nlink);
printf("%-8s", uid_to_name(info_ptr->st_uid));
printf("%-8s", gid_to_name(info_ptr->st_gid));
printf("%8ld", info_ptr->st_size);
printf("%.12s", 4 + ctime(&info_ptr->st_mtime));
printf("%s\n", filename);
}
/*ID to string*/
void mode_to_letters(int mode, char *modestr)
{
strcpy(modestr, "----------");
if(S_ISDIR(mode))
modestr[0] = 'd';
if(S_ISCHR(mode))
modestr[0] = 'c';
if(S_ISBLK(mode))
modestr[0] = 'b';
if(mode & S_IRUSR)
modestr[1] = 'r';
if(mode & S_IWUSR)
modestr[2] = 'w';
if(mode & S_IXUSR)
modestr[3] = 'x';
if(mode & S_IRGRP)
modestr[4] = 'r';
if(mode & S_IWGRP)
modestr[5] = 'w';
if(mode & S_IXGRP)
modestr[6] = 'x';
if(mode & S_IROTH)
modestr[7] = 'r';
if(mode & S_IWOTH)
modestr[8] = 'w';
if(mode & S_IXOTH)
modestr[9] = 'x';
}
/*get the username for string*/
char * uid_to_name(uid_t uid)
{
struct passwd * pw_ptr;
static char numstr[10];
if((pw_ptr = getpwuid(uid)) == NULL)
{
sprintf(numstr, "%d", uid);
return numstr;
}
else
return pw_ptr->pw_name;
}
/*get the groupname for string*/
char * gid_to_name(gid_t gid)
{
struct group * gr_ptr;
static char numstr[10];
if((gr_ptr = getgrgid(gid)) == NULL)
{
sprintf(numstr, "%d", gid);
return numstr;
}
else
return gr_ptr->gr_name;
}
类似ls命令程序
最新推荐文章于 2023-01-06 22:09:49 发布