linux获取文件信息

#include <stdio.h >
#include <stdlib.h>
#include <pwd.h >
#include <grp.h >
#include <sys/stat.h >
#include <sys/types.h >
#include  <dirent.h >
#include <time.h >
#include <fcntl.h >
#include <string.h >

void getfilepath(char *filename)
{
int len = strlen(filename);
int i = len;
if(filename[i] != '/'){
i--;
}
filename[i+1]='\0';
}
void getfileinfo(char *filename, char *d_name)
{
struct stat fileinfo;
if(stat(filename, &fileinfo)<0)
perror("stat");
//判断文件类型
if(S_ISREG(fileinfo.st_mode))
printf("-");
else if(S_ISDIR(fileinfo.st_mode))
printf("d");
else if(S_ISCHR(fileinfo.st_mode))
printf("c");
else if(S_ISBLK(fileinfo.st_mode))
printf("b");
else if(S_ISFIFO(fileinfo.st_mode))
printf("p");
else if((fileinfo.st_mode & S_IFMT) == S_IFLNK)
printf("l");
else if(S_ISSOCK(fileinfo.st_mode))
printf("s");
//获取文件权限
int i;
char str[] = "xwr-";
for(i=8; i >=0; i--)
if(fileinfo.st_mode & 1<<i)
printf("%c",str[i%3]);
else
printf("%c", str[3]);

printf(" %3u ", fileinfo.st_nlink);
printf("%s ", getpwuid(fileinfo.st_uid)->pw_name);
printf("%s ", getgrgid(fileinfo.st_gid)->gr_name);
printf("%8ld ", fileinfo.st_size);


struct tm *pt;
pt = localtime(&fileinfo.st_atime);
printf("%02d-%02d %02d:%02d ", pt->tm_mon+1, pt->tm_mday,
pt->tm_hour, pt->tm_min);
//printf("%s", filename);
printf("%s", d_name);
printf("\n");


}
int main(int argc, char **argv)
{
if(argc <2){
exit(1);
}
//int fd;
//fd = open(argv[1], O_RDWR);
DIR *pd;
if((pd = opendir(argv[1]))== NULL){
perror("opendir");
exit(1);
}
struct dirent *dir;
char path[255] ,fullname[255];
strcpy(path, argv[1]);
getfilepath(path);
while((dir=readdir(pd)) != NULL){
bzero(fullname,255);
strcpy(fullname,path);
//printf("%s\n", dir->d_name);

strcat(fullname,dir->d_name);
//printf("%s\n", fullname);
//getfileinfo(dir->d_name);
getfileinfo(fullname, dir->d_name);
}
//perror("readdir");
return 0;
}

运行结果:


</i)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30108475/viewspace-1822871/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/30108475/viewspace-1822871/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值