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);
}
执行结果如下: