实现linux ls -l的功能(简易模仿 欢迎指正 粗糙勿喷)
作者:互联网
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#include <dirent.h>
char* file_time(time_t t,char* str)
{
struct tm* it = localtime(&t);
sprintf(str,"%4d-%02d-%02d %02d:%02d:%02d",it->tm_year+1900,it->tm_mon+1,it->tm_mday,it->tm_hour,it->tm_min,it->tm_sec);
return str;
}
char* file_mode(mode_t m,char* str)
{
if(S_ISREG(m))
str[0] = '-';
else if(S_ISDIR(m))
str[0] = 'd';
else if(S_ISCHR(m))
str[0] = 'c';
else if(S_ISBLK(m))
str[0] = 'b';
else if(S_ISFIFO(m))
str[0] = 'q';
else if(S_ISLNK(m))
str[0] = 'l';
else if(S_ISSOCK(m))
str[0] = 's';
else
str[0] = '?';
str[1] = '\0';
strcat(str,S_IRUSR&m?"r":"-");
strcat(str,S_IWUSR&m?"w":"-");
strcat(str,S_IXUSR&m?"x":"-");
strcat(str,S_IRGRP&m?"r":"-");
strcat(str,S_IWGRP&m?"w":"-");
strcat(str,S_IXGRP&m?"x":"-");
strcat(str,S_IROTH&m?"r":"-");
strcat(str,S_IWOTH&m?"w":"-");
strcat(str,S_IXOTH&m?"x":"-");
return str;
}
int main()
{
DIR* dp = opendir(".");
if(NULL == dp)
{
perror("opendir");
return -1;
}
struct dirent* de = readdir(dp);
struct stat buf = {};
char str[50] = {};
for(de; NULL!=de;de=readdir(dp))
{
stat(de->d_name,&buf);
printf("%s ",file_mode(buf.st_mode,str));
printf("zhizhen ");
printf("zhizhen ");
printf("%s ",file_time(buf.st_mtime,str));
printf("%s\n",de->d_name);
}
}
标签:de,strcat,else,tm,指正,ls,str,linux,include 来源: https://blog.csdn.net/weixin_44916364/article/details/97486942