linux下文件读取函数,Linux Stat函数(获取文件详细信息) | 人人学技术

//============================================================================

// Name : stat.cpp

// Author : Mars

// Version :

// Copyright : Your copyright notice

// Description :

//============================================================================

#include

#include

#include

#include

#include

#include

#include

#include

#include

bool get_file_info_stat(const char *file_name, char *line,struct stat *s_buff)

{

char date[16];

char mode[11] = "----------";

line[0]='\0';

struct passwd * pass_info = getpwuid(s_buff->st_uid); //通过用户的uid查找用户的passwd数据

if(pass_info!=NULL) {

//依参数gid指定的组识别码逐一搜索组文件,找到时便将该组的数据以group结构返回

struct group * group_info = getgrgid(s_buff->st_gid);

if(group_info!=NULL) {

int b_mask = s_buff->st_mode & S_IFMT;

if(b_mask == S_IFDIR) {

mode[0]='d';

} else if(b_mask == S_IFREG){

mode[0]='-';

} else {

return false;

}

mode[1] = (s_buff->st_mode & S_IRUSR)?'r':'-';

mode[2] = (s_buff->st_mode & S_IWUSR)?'w':'-';

mode[3] = (s_buff->st_mode & S_IXUSR)?'x':'-';

mode[4] = (s_buff->st_mode & S_IRGRP)?'r':'-';

mode[5] = (s_buff->st_mode & S_IWGRP)?'w':'-';

mode[6] = (s_buff->st_mode & S_IXGRP)?'x':'-';

mode[7] = (s_buff->st_mode & S_IROTH)?'r':'-';

mode[8] = (s_buff->st_mode & S_IWOTH)?'w':'-';

mode[9] = (s_buff->st_mode & S_IXOTH)?'x':'-';

strftime(date,13,"%b %d %H:%M",localtime(&(s_buff->st_mtime)));

sprintf(line,"%s %3d %-4s %-4s %8d %12s %s\n",mode,s_buff->st_nlink,pass_info->pw_name,group_info->gr_name,s_buff->st_size,date,file_name);

return true;

}

}

return false;

}

bool is_special_dir(const char *dir)

{

if(dir==NULL)

return true;

int len = strlen(dir);

if(len>2)

return false;

if(dir[0]!='.')

return false;

if(len==1)

return true;

if(dir[1]=='.')

return true;

return false;

}

bool get_file_info(const char *file_name, char *line)

{

if(line==NULL)

return false;

struct stat s_buff;

if(is_special_dir(file_name))

return false;

int status = stat(file_name,&s_buff); //获取文件对应属性

if(status==0) {

return get_file_info_stat(file_name,line,&s_buff);

}

return false;

}

int main(int argc, char** argv)

{

char line[300];

char path[128] = {'\0'};

getcwd(path, 128); //获取当前工作路径

DIR* dir = opendir(path); //打开目录句柄

if(dir == NULL){

printf("opendir failed!");

return 1;

}

while(1) {

struct dirent *d_next = readdir(dir); //读取目录

if(d_next==NULL)

break;

line[0]='\0';

if(get_file_info(d_next->d_name,line)) {

printf("%s",line);

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值