#include
#include
DIR *opendir(const char *p a t h n a m e ) ;
返回:若成功则为指针,若出错则为N U L L
struct dirent *readdir(DIR *d p ) ;
返回:若成功则为指针,若在目录尾或出错则为N ULL
int closedir(DIR *d p ) ;
返回:若成功则为0,若出错则为-1
D I R结构是一个内部结构,它由这四个函数用来保存正被读的目录的有关信息。其作用类
似于F I L E结构。由o p e n d i r返回的指向D I R结构的指针由另外三个函数使用。o p e n d i r执行初始化操作,使第
一个r e a d d i r读目录中的第一个目录项。目录中各目录项的顺序与实现有关。它们通常并不按字
母顺序排列。
程序:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main(int argc ,char **argv)
{
DIR *pDir = NULL;
struct dirent *pDirent = NULL;
if((pDir = opendir("./")) == NULL) //读取目录
{
switch (errno)
{
case EACCES:
cout << "Permission denied." << endl;
break;
case EMFILE:
cout << " Too many file descriptors in use by process." << endl;
break;
case ENFILE:
cout << " Too many files are currently open in the system." << endl;
break;
case ENOENT:
cout << " Directory does not exist, or name is an empty string." << endl;
break;
case ENOMEM:
cout << " Insufficient memory to complete the operation." << endl;
break;
case ENOTDIR:
cout << " name is not a directory." << endl;
break;
default:
cout << "unknow error" << endl;
}
return -1;
}
int i = 0;
while(true)
{
i++;
pDirent = readdir(pDir) ; //读取单一文件
if(pDirent == NULL)
{
cout<
break;
}
if ((strcmp((const char *)pDirent->d_name, ".") == 0) ||(strcmp((const char *)pDirent->d_name, "..") == 0))
{
continue;
}
printf("file name:%s\n",pDirent->d_name);
char cNewDir[1024];
memset(cNewDir, 0, sizeof(cNewDir));
sprintf(cNewDir, "%s/%s", "./", (char *)pDirent->d_name);
struct stat mstat;
memset(&mstat,0,sizeof(mstat));
if(lstat(cNewDir,&mstat) == -1) //获取文件属性结构 ,此处需要使用lstat,如使用stat,则不能判断链接文件的信息 { perror("stat:"); continue; } if(S_ISDIR(mstat.st_mode)) //判断是否是目录 { printf("file:%s is a directory\n",pDirent->d_name); } else if(S_ISREG(mstat.st_mode)) { printf("file:%s is a regular file.\n",pDirent->d_name); } else if(S_ISCHR(mstat.st_mode)) { printf("file:%s is a character special file.\n",pDirent->d_name); } else if(S_ISBLK(mstat.st_mode)) { printf("file:%s is a block file.\n",pDirent->d_name); } else if(S_ISFIFO(mstat.st_mode)) { printf("file:%s is a fifo file.\n",pDirent->d_name); } else if(S_ISLNK(mstat.st_mode)) { printf("file:%s is a symbolic link file.\n",pDirent->d_name); } else if(S_ISSOCK(mstat.st_mode)) { printf("file:%s is a socket file.\n",pDirent->d_name); } else { printf("file:%s is an unknown type file.\n",pDirent->d_name); } } closedir(pDir); return 0; }