#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
void printdir(char *buf,int depth)
{
int mode;
DIR *dp;
char per[11]={"----------"};
char uname[20];
char gname[20];
struct stat statbuf;
struct dirent *entry;
if((dp=opendir(buf))== NULL) //先判斷目錄是否存在,獲取目錄中有關信息內容
{
fprintf(stderr,"cannot open directory %s\n",buf);
return ;
}
chdir(buf); //切換到要遍歷的目錄
while((entry=readdir(dp))!=NULL) //讀取到目錄下的所有文件
{
lstat(entry->d_name,&statbuf); //獲取目錄的文件信息通過文件名filename獲取文件詳細信息,並保存在buf所指的結構體stat中
if(S_ISDIR(statbuf.st_mode)) //is a directorty
{
if(strcmp(entry->d_name,".")==0 || //如果是. 或者 .. 跳過
strcmp(entry->d_name,"..")==0)
continue;
printf(" %*s%s/\n",depth,"",entry->d_name);
printdir(entry->d_name,depth+4); //遞歸
}
else // is a file
{
/*檢查權限*/
if((mode=(statbuf.st_mode & S_IRUSR))==S_IRUSR)
per[1]='r';
if((mode=(statbuf.st_mode & S_IWUSR))==S_IWUSR)
per[2]='w';
if((mode=(statbuf.st_mode & S_IXUSR))==S_IXUSR)
per[3]='x';
if((mode=(statbuf.st_mode & S_IRGRP))==S_IRGRP)
per[4]='r';
if((mode=(statbuf.st_mode & S_IWGRP))==S_IWGRP)
per[5]='w';
if((mode=(statbuf.st_mode & S_IXGRP))==S_IXGRP)
per[6]='x';
if((mode=(statbuf.st_mode & S_IROTH))==S_IROTH)
per[7]='r';
if((mode=(statbuf.st_mode & S_IWOTH))==S_IWOTH)
per[8]='w';
if((mode=(statbuf.st_mode & S_IXOTH))==S_IXOTH)
per[9]='x';
per[10]='\0';
getuidoid(&statbuf,uname,gname); //獲取文件的uid oid
printf("%*s %s %s %s %s\n",depth,"",per,uname,gname,entry->d_name);
}
}
chdir("..");
closedir(dp);
}
void getuidoid(struct stat *buf,char *uname,char *gname)
{ //通過etc/passwd文件 通過uid oid 找到對應字段的文件所有者所屬組
int uid;
int gid;
char message[50];
FILE *fp;
fp=fopen("/etc/passwd","r");
while((fscanf(fp,"%s",message))!=EOF)
{
sscanf(message,"%*[^:]%*c%*c%*c%d%*c%d",&uid,&gid);
if(buf->st_uid==uid)
{
sscanf(message,"%[^:]",uname);
sscanf(message,"%[^:]",gname);
}
}
fclose(fp);
}
int main(int argc,char *argv[])
{
char *topdir="."; //默認是當然目錄 可以通過命令行更改要遍歷目錄的位置
if(argc>=2)
topdir=argv[1];
printdir(topdir,0);
return 0;
}
linux下c語言遞歸實現ls -l功能
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.