Linux C判断文件是否为目录或者是普通文件

主要函数: stat(),opendir(),readdir(),

主要结构体:struct dirent  和 struct stat

主要宏:S_ISDIR(),     S_ISREG()


函数 stat()用于获取一个文件路径的信息,并把获取到的信息放到结构体 struct stat 中

函数 opendir()用于生成一个目录指针DIR

函数readdir()用于读取目录指针 DIR 中的信息,返回的值为一个 struct dirent 结构体


结构体struct dirent 用于保存一个目录的属性。这里用到的只是该结构体的 d_name 成员,用于保存目录下的文件名

结构体 struct stat 用于保存 一个文件路径的信息


宏S_ISDIR()用于判断一个文件路径是不是一个目录,是则返回1,否则返回0

宏S_ISREG()用于判断一个文件路径是不是一个普通文件,是则返回1,否则返回0


下面给出代码:

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

int main(int argc, char const *argv[])
{
	char const*path = argv[1];
	struct stat s_buf;

	/*获取文件信息,把信息放到s_buf中*/
	stat(path,&s_buf);

	/*判断输入的文件路径是否目录,若是目录,则往下执行,分析目录下的文件*/
	if(S_ISDIR(s_buf.st_mode))
	{
		printf("[%s] it is a dir\n",path);
		struct dirent *filename;
		DIR *dp = opendir(path);

		/*readdir()必须循环调用,要读完整个目录的文件,readdir才会返回NULL
		若未读完,就让他循环*/
		while(filename = readdir(dp))
		{
			/*判断一个文件是目录还是一个普通文件*/
			char file_path[200];
			bzero(file_path,200);
			strcat(file_path,path);
			strcat(file_path,"/");
			strcat(file_path,filename->d_name);
			
			/*获取文件信息,把信息放到s_buf中*/
			stat(file_path,&s_buf);

			/*判断是否目录*/
			if(S_ISDIR(s_buf.st_mode))
			{
				printf("[%s] is a dir\n",file_path);
			}

			/*判断是否为普通文件*/
			if(S_ISREG(s_buf.st_mode))
			{
				printf("[%s] is a regular file\n",file_path);
			}
		}
	}

	/*若输入的文件路径是普通文件,则打印并退出程序*/
	else if(S_ISREG(s_buf.st_mode))
	{
		printf("[%s] is a regular file\n",path);
		return 0;
	}

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值