step4 . day3 目录访问函数

和标准IO访问文件类似,Linux本着万物皆文件的原则,对文件进行访问。

涉及相关函数:DIR * opendir     closedir  readdir  chmod fchmod stat lstat   fstat  getpwuid  getgrpid

练习demo:按照ls命令的输出,使用stat函数实现。


#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>

 

int main(int argc, const char *argv[])
{
DIR *dirp;
struct dirent *dent;
struct stat buf;
struct tm *t;
char *month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
"Sept","Oct","Nov","Dec"};

dirp = opendir("/home/linux/step4/day2");
if(dirp == NULL){
perror("opendir");
return -1;
}
while((dent = readdir(dirp)) != NULL){

lstat(dent->d_name,&buf);

if(S_ISREG(buf.st_mode)) printf("-");
else if(S_ISDIR(buf.st_mode)) printf("d");
else if(S_ISCHR(buf.st_mode)) printf("c");
else if(S_ISBLK(buf.st_mode)) printf("b");
else if(S_ISFIFO(buf.st_mode)) printf("p");
else if(S_ISLNK(buf.st_mode)) printf("l");
else printf("s");

if(S_IRUSR & buf.st_mode) printf("r");
else printf("-");
if(S_IWUSR & buf.st_mode) printf("w");
else printf("-");
if(S_IXUSR & buf.st_mode) printf("x");
else printf("-");
if(S_IRGRP & buf.st_mode) printf("r");
else printf("-");
if(S_IWGRP & buf.st_mode) printf("w");
else printf("-");
if(S_IXGRP & buf.st_mode) printf("x");
else printf("-");
if(S_IROTH & buf.st_mode) printf("r");
else printf("-");
if(S_IWOTH & buf.st_mode) printf("w");
else printf("-");
if(S_IXOTH & buf.st_mode) printf("x");
else printf("-");

printf("%2d",buf.st_nlink);
printf(" %s %s",getpwuid(buf.st_uid)->pw_name,getgrgid(buf.st_gid)->gr_name);
printf(" %6ld",buf.st_size);
t = localtime(&(buf.st_atime));
printf(" %s %2d %02d:%02d",month[t->tm_mon],t->tm_mday,t->tm_hour,t->tm_sec);

printf(" %s\n",dent->d_name);
}
closedir(dirp);
return 0;
}

转载于:https://www.cnblogs.com/huiji12321/p/11305698.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值