index();-----------------------------------------------------------------
index第一次遇到字符c,rindex最后一次遇到字符c,返回值都是从那个位置开始往后的字符串地址
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
#include <string.h>int do_ls_file(const char *filename)
{//stat --获取文件属性信息 struct stat st;if (stat(filename,&st) < 0) //"Music" stat("./Music",&st) //"~/Music"{perror("stat fail");return -1;}//1.打印 文件类型switch(st.st_mode & S_IFMT){case S_IFSOCK:putchar('s');break;case S_IFLNK:putchar('l');break;case S_IFREG:putchar('-');break;case S_IFBLK:putchar('b');break;case S_IFCHR:putchar('c');break;case S_IFIFO:putchar('p');break;case S_IFDIR:putchar('d');break;default:putchar('?');break;}//2.文件权限 st.st_mode&S_IRUSR?putchar('r'):putchar('-'); st.st_mode&S_IWUSR?putchar('w'):putchar('-'); st.st_mode&S_IXUSR?putchar('x'):putchar('-'); st.st_mode&S_IRGRP?putchar('r'):putchar('-'); st.st_mode&S_IWGRP?putchar('w'):putchar('-'); st.st_mode&S_IXGRP?putchar('x'):putchar('-'); st.st_mode&S_IROTH?putchar('r'):putchar('-'); st.st_mode&S_IWOTH?putchar('w'):putchar('-'); st.st_mode&S_IXOTH?putchar('x'):putchar('-'); //3.硬链接数printf(" %ld",st.st_nlink);//4.所属用户 printf(" %s",getpwuid(st.st_uid)->pw_name);//5.所属组printf(" %s",getgrgid(st.st_gid)->gr_name);//6.大小 printf(" %ld",st.st_size);//7.最后修改时间 struct tm *ptm = localtime(&st.st_mtime); printf(" %02d月%02d %02d:%02d",ptm->tm_mon+1,ptm->tm_mday,ptm->tm_hour,ptm->tm_min);//8.名字printf(" %s\n",rindex(filename,'/')+1); //filename是人为加上带路径的文件名return 0;
}int do_ls_dir(const char *dirname)
{DIR *dir = opendir(dirname);if (dir == NULL){perror("opendir fail");return -1;}struct dirent *pdir = NULL;while (pdir=readdir(dir)){// printf("name = %s\n",pdir->d_name); //"Music"char path[1024] = {0};// "~"// "~/" if(pdir->d_name[0] != '.'){dirname[strlen(dirname)-1] == '/'?sprintf(path,"%s%s",dirname,pdir->d_name):sprintf(path,"%s/%s",dirname,pdir->d_name);//带了路径的文件名do_ls_file(path); //"~/Music"}}closedir(dir);
}//ls 1.txt
//ls dir
int main(int argc, const char *argv[])
{if (argc != 2){printf("Usage: %s <filename>\n",argv[0]);return -1;}// do_ls_file(argv[1]);do_ls_dir(argv[1]);return 0;
}