Directory operations in Linux C + +

Source: Internet
Author: User
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  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.