linux下目录扫描程序

题目要求: 设计一个目录扫描程序,输入目录名,扫描该目录下的文件,依次输出扫描的文件名、文件类型、文件大小,inode

代码:

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<dirent.h>

void printdir(char *dir,int depth){///depth 控制缩进
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;///文件类型
    if((dp=opendir(dir))==NULL){
        printf("open %s error\n",dir);
        return ;
    }
    chdir(dir);///切换到当前目录
    while((entry=readdir(dp))!=NULL){
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode)){///如果是目录,递归遍历输出
            printf("%*s name:%s/  type:%d  inode:%d\n",depth,"",entry->d_name,
                   statbuf.st_mode,statbuf.st_size,entry->d_ino);
            ///忽略.和..目录
            if(strcmp(".",entry->d_name)==0 || strcmp("..",entry->d_name)==0)
                continue;
            printdir(entry->d_name,depth+4);
        }
        else{///如果是文件,直接输出
            printf("%*s name:%s/  type:%d  inode:%d\n",depth,"",entry->d_name,
                   statbuf.st_mode,statbuf.st_size,entry->d_ino);
        }
    }
    chdir("..");///切换到上层目录
    closedir(dp);

}

int main(){
    char dir[30];
    printf("input dir\n");
    scanf("%s",dir);

    printdir(dir,0);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值