Advertisement
obernardovieira

dirent.h

Jul 30th, 2013
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.81 KB | None | 0 0
  1. /*****************************************************************************
  2.  * dirent.h - dirent API for Microsoft Visual Studio
  3.  *
  4.  * Copyright (C) 2006 Toni Ronkko
  5.  *
  6.  * Permission is hereby granted, free of charge, to any person obtaining
  7.  * a copy of this software and associated documentation files (the
  8.  * ``Software''), to deal in the Software without restriction, including
  9.  * without limitation the rights to use, copy, modify, merge, publish,
  10.  * distribute, sublicense, and/or sell copies of the Software, and to
  11.  * permit persons to whom the Software is furnished to do so, subject to
  12.  * the following conditions:
  13.  *
  14.  * The above copyright notice and this permission notice shall be included
  15.  * in all copies or substantial portions of the Software.
  16.  *
  17.  * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18.  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19.  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  20.  * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR
  21.  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  22.  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23.  * OTHER DEALINGS IN THE SOFTWARE.
  24.  *
  25.  * Aug 11, 2010, Toni Ronkko
  26.  * Added d_type and d_namlen fields to dirent structure.  The former is
  27.  * especially useful for determining whether directory entry represents a
  28.  * file or a directory.  For more information, see
  29.  * http://www.delorie.com/gnu/docs/glibc/libc_270.html
  30.  *
  31.  * Aug 11, 2010, Toni Ronkko
  32.  * Improved conformance to the standards.  For example, errno is now set
  33.  * properly on failure and assert() is never used.  Thanks to Peter Brockam
  34.  * for suggestions.
  35.  *
  36.  * Aug 11, 2010, Toni Ronkko
  37.  * Fixed a bug in rewinddir(): when using relative directory names, change
  38.  * of working directory no longer causes rewinddir() to fail.
  39.  *
  40.  * Dec 15, 2009, John Cunningham
  41.  * Added rewinddir member function
  42.  *
  43.  * Jan 18, 2008, Toni Ronkko
  44.  * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string
  45.  * between multi-byte and unicode representations.  This makes the
  46.  * code simpler and also allows the code to be compiled under MingW.  Thanks
  47.  * to Azriel Fasten for the suggestion.
  48.  *
  49.  * Mar 4, 2007, Toni Ronkko
  50.  * Bug fix: due to the strncpy_s() function this file only compiled in
  51.  * Visual Studio 2005.  Using the new string functions only when the
  52.  * compiler version allows.
  53.  *
  54.  * Nov  2, 2006, Toni Ronkko
  55.  * Major update: removed support for Watcom C, MS-DOS and Turbo C to
  56.  * simplify the file, updated the code to compile cleanly on Visual
  57.  * Studio 2005 with both unicode and multi-byte character strings,
  58.  * removed rewinddir() as it had a bug.
  59.  *
  60.  * Aug 20, 2006, Toni Ronkko
  61.  * Removed all remarks about MSVC 1.0, which is antiqued now.  Simplified
  62.  * comments by removing SGML tags.
  63.  *
  64.  * May 14 2002, Toni Ronkko
  65.  * Embedded the function definitions directly to the header so that no
  66.  * source modules need to be included in the Visual Studio project.  Removed
  67.  * all the dependencies to other projects so that this very header can be
  68.  * used independently.
  69.  *
  70.  * May 28 1998, Toni Ronkko
  71.  * First version.
  72.  *****************************************************************************/
  73. #ifndef DIRENT_H
  74. #define DIRENT_H
  75.  
  76. #define WIN32_LEAN_AND_MEAN
  77. #include <windows.h>
  78. #include <string.h>
  79. #include <stdlib.h>
  80. #include <sys/types.h>
  81. #include <sys/stat.h>
  82. #include <errno.h>
  83.  
  84. /* File type and permission flags for stat() */
  85. #if defined(_MSC_VER)  &&  !defined(S_IREAD)
  86. # define S_IFMT   _S_IFMT                      /* file type mask */
  87. # define S_IFDIR  _S_IFDIR                     /* directory */
  88. # define S_IFCHR  _S_IFCHR                     /* character device */
  89. # define S_IFFIFO _S_IFFIFO                    /* pipe */
  90. # define S_IFREG  _S_IFREG                     /* regular file */
  91. # define S_IREAD  _S_IREAD                     /* read permission */
  92. # define S_IWRITE _S_IWRITE                    /* write permission */
  93. # define S_IEXEC  _S_IEXEC                     /* execute permission */
  94. #endif
  95. #define S_IFBLK   0                            /* block device */
  96. #define S_IFLNK   0                            /* link */
  97. #define S_IFSOCK  0                            /* socket */
  98.  
  99. #if defined(_MSC_VER)
  100. # define S_IRUSR  S_IREAD                      /* read, user */
  101. # define S_IWUSR  S_IWRITE                     /* write, user */
  102. # define S_IXUSR  0                            /* execute, user */
  103. # define S_IRGRP  0                            /* read, group */
  104. # define S_IWGRP  0                            /* write, group */
  105. # define S_IXGRP  0                            /* execute, group */
  106. # define S_IROTH  0                            /* read, others */
  107. # define S_IWOTH  0                            /* write, others */
  108. # define S_IXOTH  0                            /* execute, others */
  109. #endif
  110.  
  111. /* Indicates that d_type field is available in dirent structure */
  112. #define _DIRENT_HAVE_D_TYPE
  113.  
  114. /* File type flags for d_type */
  115. #define DT_UNKNOWN  0
  116. #define DT_REG      S_IFREG
  117. #define DT_DIR      S_IFDIR
  118. #define DT_FIFO     S_IFFIFO
  119. #define DT_SOCK     S_IFSOCK
  120. #define DT_CHR      S_IFCHR
  121. #define DT_BLK      S_IFBLK
  122.  
  123. /* Macros for converting between st_mode and d_type */
  124. #define IFTODT(mode) ((mode) & S_IFMT)
  125. #define DTTOIF(type) (type)
  126.  
  127. /*
  128.  * File type macros.  Note that block devices, sockets and links cannot be
  129.  * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
  130.  * only defined for compatibility.  These macros should always return false
  131.  * on Windows.
  132.  */
  133. #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFFIFO)
  134. #define S_ISDIR(mode)  (((mode) & S_IFMT) == S_IFDIR)
  135. #define S_ISREG(mode)  (((mode) & S_IFMT) == S_IFREG)
  136. #define S_ISLNK(mode)  (((mode) & S_IFMT) == S_IFLNK)
  137. #define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
  138. #define S_ISCHR(mode)  (((mode) & S_IFMT) == S_IFCHR)
  139. #define S_ISBLK(mode)  (((mode) & S_IFMT) == S_IFBLK)
  140.  
  141. #ifdef __cplusplus
  142. extern "C" {
  143. #endif
  144.  
  145.  
  146. typedef struct dirent
  147. {
  148.    char d_name[MAX_PATH + 1];                  /* File name */
  149.    size_t d_namlen;                            /* Length of name without \0 */
  150.    int d_type;                                 /* File type */
  151. } dirent;
  152.  
  153.  
  154. typedef struct DIR
  155. {
  156.    dirent           curentry;                  /* Current directory entry */
  157.    WIN32_FIND_DATAA find_data;                 /* Private file data */
  158.    int              cached;                    /* True if data is valid */
  159.    HANDLE           search_handle;             /* Win32 search handle */
  160.    char             patt[MAX_PATH + 3];        /* Initial directory name */
  161. } DIR;
  162.  
  163.  
  164. /* Forward declarations */
  165. static DIR *opendir(const char *dirname);
  166. static struct dirent *readdir(DIR *dirp);
  167. static int closedir(DIR *dirp);
  168. static void rewinddir(DIR* dirp);
  169.  
  170.  
  171. /* Use the new safe string functions introduced in Visual Studio 2005 */
  172. #if defined(_MSC_VER) && _MSC_VER >= 1400
  173. # define DIRENT_STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE)
  174. #else
  175. # define DIRENT_STRNCPY(dest,src,size) strncpy((dest),(src),(size))
  176. #endif
  177.  
  178. /* Set errno variable */
  179. #if defined(_MSC_VER)
  180. #define DIRENT_SET_ERRNO(x) _set_errno (x)
  181. #else
  182. #define DIRENT_SET_ERRNO(x) (errno = (x))
  183. #endif
  184.  
  185.  
  186. /*****************************************************************************
  187.  * Open directory stream DIRNAME for read and return a pointer to the
  188.  * internal working area that is used to retrieve individual directory
  189.  * entries.
  190.  */
  191. static DIR *opendir(const char *dirname)
  192. {
  193.    DIR *dirp;
  194.  
  195.    /* ensure that the resulting search pattern will be a valid file name */
  196.    if (dirname == NULL) {
  197.       DIRENT_SET_ERRNO (ENOENT);
  198.       return NULL;
  199.    }
  200.    if (strlen (dirname) + 3 >= MAX_PATH) {
  201.       DIRENT_SET_ERRNO (ENAMETOOLONG);
  202.       return NULL;
  203.    }
  204.  
  205.    /* construct new DIR structure */
  206.    dirp = (DIR*) malloc (sizeof (struct DIR));
  207.    if (dirp != NULL) {
  208.       int error;
  209.  
  210.       /*
  211.        * Convert relative directory name to an absolute directory one.  This
  212.        * allows rewinddir() to function correctly when the current working
  213.        * directory is changed between opendir() and rewinddir().
  214.        */
  215.       if (GetFullPathNameA (dirname, MAX_PATH, dirp->patt, NULL)) {
  216.          char *p;
  217.  
  218.          /* append the search pattern "\\*\0" to the directory name */
  219.          p = strchr (dirp->patt, '\0');
  220.          if (dirp->patt < p  &&  *(p-1) != '\\'  &&  *(p-1) != ':') {
  221.            *p++ = '\\';
  222.          }
  223.          *p++ = '*';
  224.          *p = '\0';
  225.  
  226.          /* open directory stream and retrieve the first entry */
  227.          dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data);
  228.          if (dirp->search_handle != INVALID_HANDLE_VALUE) {
  229.             /* a directory entry is now waiting in memory */
  230.             dirp->cached = 1;
  231.             error = 0;
  232.          } else {
  233.             /* search pattern is not a directory name? */
  234.             DIRENT_SET_ERRNO (ENOENT);
  235.             error = 1;
  236.          }
  237.       } else {
  238.          /* buffer too small */
  239.          DIRENT_SET_ERRNO (ENOMEM);
  240.          error = 1;
  241.       }
  242.  
  243.       if (error) {
  244.          free (dirp);
  245.          dirp = NULL;
  246.       }
  247.    }
  248.  
  249.    return dirp;
  250. }
  251.  
  252.  
  253. /*****************************************************************************
  254.  * Read a directory entry, and return a pointer to a dirent structure
  255.  * containing the name of the entry in d_name field.  Individual directory
  256.  * entries returned by this very function include regular files,
  257.  * sub-directories, pseudo-directories "." and "..", but also volume labels,
  258.  * hidden files and system files may be returned.
  259.  */
  260. static struct dirent *readdir(DIR *dirp)
  261. {
  262.    DWORD attr;
  263.    if (dirp == NULL) {
  264.       /* directory stream did not open */
  265.       DIRENT_SET_ERRNO (EBADF);
  266.       return NULL;
  267.    }
  268.  
  269.    /* get next directory entry */
  270.    if (dirp->cached != 0) {
  271.       /* a valid directory entry already in memory */
  272.       dirp->cached = 0;
  273.    } else {
  274.       /* get the next directory entry from stream */
  275.       if (dirp->search_handle == INVALID_HANDLE_VALUE) {
  276.          return NULL;
  277.       }
  278.       if (FindNextFileA (dirp->search_handle, &dirp->find_data) == FALSE) {
  279.          /* the very last entry has been processed or an error occured */
  280.          FindClose (dirp->search_handle);
  281.          dirp->search_handle = INVALID_HANDLE_VALUE;
  282.          return NULL;
  283.       }
  284.    }
  285.  
  286.    /* copy as a multibyte character string */
  287.    DIRENT_STRNCPY ( dirp->curentry.d_name,
  288.              dirp->find_data.cFileName,
  289.              sizeof(dirp->curentry.d_name) );
  290.    dirp->curentry.d_name[MAX_PATH] = '\0';
  291.  
  292.    /* compute the length of name */
  293.    dirp->curentry.d_namlen = strlen (dirp->curentry.d_name);
  294.  
  295.    /* determine file type */
  296.    attr = dirp->find_data.dwFileAttributes;
  297.    if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
  298.       dirp->curentry.d_type = DT_CHR;
  299.    } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  300.       dirp->curentry.d_type = DT_DIR;
  301.    } else {
  302.       dirp->curentry.d_type = DT_REG;
  303.    }
  304.    return &dirp->curentry;
  305. }
  306.  
  307.  
  308. /*****************************************************************************
  309.  * Close directory stream opened by opendir() function.  Close of the
  310.  * directory stream invalidates the DIR structure as well as any previously
  311.  * read directory entry.
  312.  */
  313. static int closedir(DIR *dirp)
  314. {
  315.    if (dirp == NULL) {
  316.       /* invalid directory stream */
  317.       DIRENT_SET_ERRNO (EBADF);
  318.       return -1;
  319.    }
  320.  
  321.    /* release search handle */
  322.    if (dirp->search_handle != INVALID_HANDLE_VALUE) {
  323.       FindClose (dirp->search_handle);
  324.       dirp->search_handle = INVALID_HANDLE_VALUE;
  325.    }
  326.  
  327.    /* release directory structure */
  328.    free (dirp);
  329.    return 0;
  330. }
  331.  
  332.  
  333. /*****************************************************************************
  334.  * Resets the position of the directory stream to which dirp refers to the
  335.  * beginning of the directory.  It also causes the directory stream to refer
  336.  * to the current state of the corresponding directory, as a call to opendir()
  337.  * would have done.  If dirp does not refer to a directory stream, the effect
  338.  * is undefined.
  339.  */
  340. static void rewinddir(DIR* dirp)
  341. {
  342.    if (dirp != NULL) {
  343.       /* release search handle */
  344.       if (dirp->search_handle != INVALID_HANDLE_VALUE) {
  345.          FindClose (dirp->search_handle);
  346.       }
  347.  
  348.       /* open new search handle and retrieve the first entry */
  349.       dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data);
  350.       if (dirp->search_handle != INVALID_HANDLE_VALUE) {
  351.          /* a directory entry is now waiting in memory */
  352.          dirp->cached = 1;
  353.       } else {
  354.          /* failed to re-open directory: no directory entry in memory */
  355.          dirp->cached = 0;
  356.       }
  357.    }
  358. }
  359.  
  360.  
  361. #ifdef __cplusplus
  362. }
  363. #endif
  364. #endif /*DIRENT_H*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement