dir under linux.Linux下的类dir程序.

11 篇文章 0 订阅

示例在linux如何获取文件信息.

#include  < unistd.h >
#include 
< stdio.h >
#include 
< stdlib.h >
#include 
< string .h >
#include 
< errno.h >
#include 
< sys / types.h >
#include 
< sys / stat.h >
#include 
< dirent.h >
#include 
< time.h >

static   int  get_file_size_time( const   char   * file_path, const   char   * filename)  {
    
struct stat statbuf;
    
if(stat(file_path,&statbuf) == -1{
        printf(
"Get stat on %s Error:%sn",
            filename,strerror(errno));
        
return -1;
    }

    
//获得目录
    if(S_ISDIR(statbuf.st_mode)) {
        printf(
"[%s]n",filename);
        
return 1;
    }

    
//获得文件
    if(S_ISREG(statbuf.st_mode)) {
        printf(
"%stsize:%ld bytestmodified at %s",
            filename,statbuf.st_size,
            ctime(
&statbuf.st_mtime));
    }

    
return 0;
}


int  main( int  argc, char   ** argv)  {
    DIR 
*dirp;
    
struct dirent *direntp;
    
int stats;

    
if(argc != 2{
        printf(
"Usage:%s filnamena",argv[0]);
        exit(
1);
    }

    
    
//获得文件或错误
    if((stats = get_file_size_time(argv[1],argv[1]) == 0
        
|| (stats == -1)) exit(1);
    
//获得目录
    if((dirp = opendir(argv[1])) == NULL) {
        printf(
"Open Directory %s Error:%sn",argv[1],
            strerror(errno));
        exit(
1);
    }

    printf(
"Open Dir %s success.n",argv[1]);
    
while((direntp = readdir(dirp)) != NULL) {
        
int path_length = strlen(argv[1])
            
+ strlen(direntp->d_name) + 2;
        
char *file_path = (char*)malloc(path_length * sizeof(char));
        
if(file_path == NULL) {
            fprintf(stderr,
"Not enough memory.");
            exit(
1);
        }

        strcpy(file_path,argv[
1]);
        
if(file_path[strlen(file_path) - 1!= '/')
            strcat(file_path,
"/");
        strcat(file_path,direntp
->d_name);
        
if(get_file_size_time(file_path,direntp->d_name) == -1{
            free(file_path);
            
break;
        }

        free(file_path);
    }

    closedir(dirp);
    
    
return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值