directory operations in Linux C + +
Linux directory Operations general process is: Open Directory-read the directory (files in)-Close the directory. The corresponding function is Opendir-readdir-closedir, and its prototypes are defined in/usr/include/dirent.h.
Prototype:
#include <dirent.h>
DIR *opendir (const char *dirname);
struct Dirent *readdir (DIR *dirp);
int Closedir (DIR *dirp);
Dir is the directory Stream,opendir function that returns the Dir stream type and is invoked by the Read function Readdir;
Readdir returns the dirent structure:
struct dirent
{
#ifndef __use_file_offset64
__ino_t D_ino;
__off_t D_off;
#else
__ino64_t D_ino;
__off64_t D_off;
#endif
unsigned short int d_reclen;
unsigned char d_type;
Char d_name[256]; /* We must not include limits.h! */
};
D_reclen represents the length of the record, D_type represents the file type (see later), D_name represents the filename;
Closedir return 0 indicates a successful shutdown,-1 indicates failure.
The value of the D_tpye in the dirent structure body can be the following enumeration member:
Enum
{
Dt_unknown = 0,//unknown type
# define Dt_unknown Dt_unknown
Dt_fifo = 1,//pipe
# define DT_FIFO Dt_fifo
DT_CHR = 2,//character device file
# define DT_CHR DT_CHR
Dt_dir = 4,//directory
# define Dt_dir Dt_dir
DT_BLK = 6,//block device file
# define DT_BLK dt_blk
Dt_reg = 8,//Normal file
# define Dt_reg Dt_reg
Dt_lnk = 10,//Connection file
# define Dt_lnk Dt_lnk
Dt_sock = 12,//socket type
# define Dt_sock Dt_sock
DT_WHT = 14//
# define DT_WHT DT_WHT
};
Example:
#include <dirent.h>
string Testpath;
dir* pdir = NULL;
struct dirent* ent = NULL;
Pdir = Opendir (Testpath.c_str ());
if (NULL = pdir) {
return false,
}
while (null!= (Ent=readdir PD IR))
{
if (Ent->d_type = 8)//Normal file
{
...
}
}
...
Closedir (Pdir);
Pdir = NULL;
http://blog.csdn.net/zebrince/article/details/6978774