linux c语言 实现 ls -l 功能
代码
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <sys/types.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <grp.h>
#include <dirent.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if(argc != 2){
argv[1] = "./";
}
DIR *dirp = opendir(argv[1]);
if(dirp == NULL){
perror("opendir");
return -1;
}
struct dirent *dirent = NULL;
struct stat mybuf;
int total = 0;
while(1){
dirent = readdir(dirp);
if(dirent == NULL) break;
if(strncmp(".",dirent->d_name,1)==0) continue;
stat(dirent->d_name,&mybuf);
if(S_ISREG(mybuf.st_mode)){
printf("-");
}else if(S_ISCHR(mybuf.st_mode)){
printf("c");
printf("%d %d ",major(mybuf.st_rdev),minor(mybuf.st_rdev));
}else if(S_ISDIR(mybuf.st_mode)){
printf("d");
}
#ifdef S_ISLNK
else if(S_ISLNK(mybuf.st_mode)){
printf("l");
}
#endif
printf("%c",mybuf.st_mode & (0x1<<8)?'r':'-');
printf("%c",mybuf.st_mode & (0x1<<7)?'w':'-');
printf("%c",mybuf.st_mode & (0x1<<6)?'x':'-');
printf("%c",mybuf.st_mode & (0x1<<5)?'r':'-');
printf("%c",mybuf.st_mode & (0x1<<4)?'w':'-');
printf("%c",mybuf.st_mode & (0x1<<3)?'x':'-');
printf("%c",mybuf.st_mode & (0x1<<2)?'r':'-');
printf("%c",mybuf.st_mode & (0x1<<1)?'w':'-');
printf("%c",mybuf.st_mode & (0x1<<0)?'x':'-');
printf(" %ld ",mybuf.st_nlink);
struct passwd *p = getpwuid(mybuf.st_uid);
printf("%s ",p->pw_name);
struct group *g = getgrgid(mybuf.st_gid);
printf("%s ", g->gr_name);
printf("%6ld ", mybuf.st_size);
struct tm *k = localtime(&mybuf.st_mtime);
printf("%d月 ",k->tm_mon+1);
printf("%2d ",k->tm_mday);
printf("%d:%-2d ",k->tm_hour,k->tm_min);
printf("%s",dirent->d_name);
printf("\n");
total += mybuf.st_blocks/2;
}
printf("总用量: %d\n", total);
closedir(dirp);
return 0;
}
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/210d877b47c41bdebc0aff48466f5b85.jpeg#pic_center)