linux显示指定目录下的所有文件的文件类型和文件名

linux显示指定目录下的所有文件的文件类型和文件名,并打印普通文件个数。
用到的函数:

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

readdir返回的结构体指针指向的结构体为

 struct dirent {
               ino_t          d_ino;       /* Inode number */
               off_t          d_off;       /* Not an offset; see below */
               unsigned short d_reclen;    /* Length of this record */
               unsigned char  d_type;      /* 文件类型 */
               char           d_name[256]; /* 文件名 */
           };

文件类型d_type为宏常量,所代表的具体类型如下

	  DT_BLK      This is a block device.

      DT_CHR      This is a character device.

      DT_DIR      This is a directory.

      DT_FIFO     This is a named pipe (FIFO).

      DT_LNK      This is a symbolic link.

      DT_REG      This is a regular file.

      DT_SOCK     This is a UNIX domain socket.

      DT_UNKNOWN  The file type could not be determined.

实现代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
int printInfo(char *fPath)
{
	DIR *pDir=opendir(fPath);
	struct dirent *pDent = NULL;

	//n表示普通文件个数
	int n=0;
	//str1表示路径
	char str1[300]="0";
	strcpy(str1,fPath);

	while((pDent=readdir(pDir))!=0)
	{
		if(strcmp(pDent->d_name,".")==0 || strcmp(pDent->d_name,"..")==0) continue;
		switch(pDent->d_type)
		{
			case DT_DIR:
				memset(str1,0,300);
				sprintf(str1,"%s/%s",fPath,pDent->d_name);
				
				//用递归函数去遍历fPath下的所有文件
				n+=printInfo(str1);
				//打印文件信息
				printf("目录        ");
				printf("%s",str1);
				break;
			case DT_LNK:
				printf("软连接      ");
				printf("%s/%s",str1,pDent->d_name);
				break;
			case DT_REG:
				printf("普通文件    ");
				printf("%s/%s",str1,pDent->d_name);
				n++;
				break;
			default:
				printf("其他类型文件");
				printf("%s/%s",str1,pDent->d_name);
		}
		printf("\n");
	}
	closedir(pDir);
	return n;
}

int main(int argc,char *argv[])
{
	int n=printInfo(argv[1]);
	printf("普通文件个数:%d\n",n);
	
}

执行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值