c/c++ linux下判断目录中所有文件的类型

#include <iostream>
#include <dirent.h>
using namespace std;
int main()
{
	string dirname = "./" ;
	DIR * dp ;
	struct dirent * dirp ;
	if(( dp = opendir(dirname.data()) ) == NULL){
		cout << "can not open " << dirname <<endl ;
		return 0 ;
	}
	while((dirp = readdir(dp)) != NULL){
		cout << dirp->d_name << endl ;
		if(dirp->d_type == 4){
			cout<<"===========" << "dir" << endl ;
		}else if(dirp->d_type == 8){
			cout<<"===========" << "file" << endl ;
		}else{
			cout<<"===========" << "other" << endl ;
		}
	}
	closedir(dp);
	return 0;
}

关于 struct dirent 中d_type字段的值说明如下:

enum
{
    DT_UNKNOWN = 0,         //未知类型
# define DT_UNKNOWN DT_UNKNOWN
    DT_FIFO = 1,            //管道
# define DT_FIFO DT_FIFO
    DT_CHR = 2,             //字符设备
# define DT_CHR DT_CHR
    DT_DIR = 4,             //目录
# define DT_DIR DT_DIR
    DT_BLK = 6,             //块设备
# define DT_BLK DT_BLK
    DT_REG = 8,             //常规文件
# define DT_REG DT_REG
    DT_LNK = 10,            //符号链接
# define DT_LNK DT_LNK
    DT_SOCK = 12,           //套接字
# define DT_SOCK DT_SOCK
    DT_WHT = 14             //链接
# define DT_WHT DT_WHT
};

stat 和 lstat 函数 

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

void chk(struct stat s){
    if(S_ISREG(s.st_mode)) printf("普通文件\n") ;
    else if(S_ISDIR(s.st_mode)) printf("目录\n") ;
    else if(S_ISLNK(s.st_mode)) printf("symbol link\n") ;
}
int main() {

    struct stat s ;

    stat("./mysymlink",&s) ;  // 直接读取被链接文件的属性
    chk(s) ;
    printf("%d\n",lstat("./mysymlink",&s)) ;    // 读取软链接文件的属性
    chk(s) ;
    printf("%d\n",lstat("./getenv.c",&s)) ;
    chk(s) ;
    printf("%d\n",lstat("./a",&s)) ;
    chk(s) ;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值