add a test for IA64 Debian GNU/Linux Etch.
[ruby-svn.git] / dir.c
blobb056849e0d0425486323955c425e9f819877f20c
1 /**********************************************************************
3 dir.c -
5 $Author$
6 created at: Wed Jan 5 09:51:01 JST 1994
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
16 #include <sys/types.h>
17 #include <sys/stat.h>
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
23 #if defined HAVE_DIRENT_H && !defined _WIN32
24 # include <dirent.h>
25 # define NAMLEN(dirent) strlen((dirent)->d_name)
26 #elif defined HAVE_DIRECT_H && !defined _WIN32
27 # include <direct.h>
28 # define NAMLEN(dirent) strlen((dirent)->d_name)
29 #else
30 # define dirent direct
31 # if !defined __NeXT__
32 # define NAMLEN(dirent) (dirent)->d_namlen
33 # else
34 # /* On some versions of NextStep, d_namlen is always zero, so avoid it. */
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
36 # endif
37 # if HAVE_SYS_NDIR_H
38 # include <sys/ndir.h>
39 # endif
40 # if HAVE_SYS_DIR_H
41 # include <sys/dir.h>
42 # endif
43 # if HAVE_NDIR_H
44 # include <ndir.h>
45 # endif
46 # ifdef _WIN32
47 # include "win32/dir.h"
48 # endif
49 #endif
51 #include <errno.h>
53 #ifndef HAVE_STDLIB_H
54 char *getenv();
55 #endif
57 #ifndef HAVE_STRING_H
58 char *strchr(char*,char);
59 #endif
61 #include <ctype.h>
63 #include "ruby/util.h"
65 #if !defined HAVE_LSTAT && !defined lstat
66 #define lstat stat
67 #endif
69 #ifndef CASEFOLD_FILESYSTEM
70 # if defined DOSISH || defined __VMS
71 # define CASEFOLD_FILESYSTEM 1
72 # else
73 # define CASEFOLD_FILESYSTEM 0
74 # endif
75 #endif
77 #define FNM_NOESCAPE 0x01
78 #define FNM_PATHNAME 0x02
79 #define FNM_DOTMATCH 0x04
80 #define FNM_CASEFOLD 0x08
81 #if CASEFOLD_FILESYSTEM
82 #define FNM_SYSCASE FNM_CASEFOLD
83 #else
84 #define FNM_SYSCASE 0
85 #endif
87 #define FNM_NOMATCH 1
88 #define FNM_ERROR 2
90 #define downcase(c) (nocase && ISUPPER(c) ? TOLOWER(c) : (c))
91 #define compare(c1, c2) (((unsigned char)(c1)) - ((unsigned char)(c2)))
93 /* caution: in case *p == '\0'
94 Next(p) == p + 1 in single byte environment
95 Next(p) == p in multi byte environment
97 #if defined(CharNext)
98 # define Next(p) CharNext(p)
99 #elif defined(DJGPP)
100 # define Next(p) ((p) + mblen(p, RUBY_MBCHAR_MAXSIZE))
101 #elif defined(__EMX__)
102 # define Next(p) ((p) + emx_mblen(p))
103 static inline int
104 emx_mblen(const char *p)
106 int n = mblen(p, RUBY_MBCHAR_MAXSIZE);
107 return (n < 0) ? 1 : n;
109 #endif
111 #ifndef Next /* single byte environment */
112 # define Next(p) ((p) + 1)
113 # define Inc(p) (++(p))
114 # define Compare(p1, p2) (compare(downcase(*(p1)), downcase(*(p2))))
115 #else /* multi byte environment */
116 # define Inc(p) ((p) = Next(p))
117 # define Compare(p1, p2) (CompareImpl(p1, p2, nocase))
118 static int
119 CompareImpl(const char *p1, const char *p2, int nocase)
121 const int len1 = Next(p1) - p1;
122 const int len2 = Next(p2) - p2;
123 #ifdef _WIN32
124 char buf1[10], buf2[10]; /* large enough? */
125 #endif
127 if (len1 < 0 || len2 < 0) {
128 rb_fatal("CompareImpl: negative len");
131 if (len1 == 0) return len2;
132 if (len2 == 0) return -len1;
134 #ifdef _WIN32
135 if (nocase && rb_w32_iswinnt()) {
136 if (len1 > 1) {
137 if (len1 >= sizeof(buf1)) {
138 rb_fatal("CompareImpl: too large len");
140 memcpy(buf1, p1, len1);
141 buf1[len1] = '\0';
142 CharLower(buf1);
143 p1 = buf1; /* trick */
145 if (len2 > 1) {
146 if (len2 >= sizeof(buf2)) {
147 rb_fatal("CompareImpl: too large len");
149 memcpy(buf2, p2, len2);
150 buf2[len2] = '\0';
151 CharLower(buf2);
152 p2 = buf2; /* trick */
155 #endif
156 if (len1 == 1)
157 if (len2 == 1)
158 return compare(downcase(*p1), downcase(*p2));
159 else {
160 const int ret = compare(downcase(*p1), *p2);
161 return ret ? ret : -1;
163 else
164 if (len2 == 1) {
165 const int ret = compare(*p1, downcase(*p2));
166 return ret ? ret : 1;
168 else {
169 const int ret = memcmp(p1, p2, len1 < len2 ? len1 : len2);
170 return ret ? ret : len1 - len2;
173 #endif /* environment */
175 static char *
176 bracket(
177 const char *p, /* pattern (next to '[') */
178 const char *s, /* string */
179 int flags)
181 const int nocase = flags & FNM_CASEFOLD;
182 const int escape = !(flags & FNM_NOESCAPE);
184 int ok = 0, not = 0;
186 if (*p == '!' || *p == '^') {
187 not = 1;
188 p++;
191 while (*p != ']') {
192 const char *t1 = p;
193 if (escape && *t1 == '\\')
194 t1++;
195 if (!*t1)
196 return NULL;
197 p = Next(t1);
198 if (p[0] == '-' && p[1] != ']') {
199 const char *t2 = p + 1;
200 if (escape && *t2 == '\\')
201 t2++;
202 if (!*t2)
203 return NULL;
204 p = Next(t2);
205 if (!ok && Compare(t1, s) <= 0 && Compare(s, t2) <= 0)
206 ok = 1;
208 else
209 if (!ok && Compare(t1, s) == 0)
210 ok = 1;
213 return ok == not ? NULL : (char *)p + 1;
216 /* If FNM_PATHNAME is set, only path element will be matched. (upto '/' or '\0')
217 Otherwise, entire string will be matched.
218 End marker itself won't be compared.
219 And if function succeeds, *pcur reaches end marker.
221 #define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p))
222 #define ISEND(p) (!*(p) || (pathname && *(p) == '/'))
223 #define RETURN(val) return *pcur = p, *scur = s, (val);
225 static int
226 fnmatch_helper(
227 const char **pcur, /* pattern */
228 const char **scur, /* string */
229 int flags)
231 const int period = !(flags & FNM_DOTMATCH);
232 const int pathname = flags & FNM_PATHNAME;
233 const int escape = !(flags & FNM_NOESCAPE);
234 const int nocase = flags & FNM_CASEFOLD;
236 const char *ptmp = 0;
237 const char *stmp = 0;
239 const char *p = *pcur;
240 const char *s = *scur;
242 if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
243 RETURN(FNM_NOMATCH);
245 while (1) {
246 switch (*p) {
247 case '*':
248 do { p++; } while (*p == '*');
249 if (ISEND(UNESCAPE(p))) {
250 p = UNESCAPE(p);
251 RETURN(0);
253 if (ISEND(s))
254 RETURN(FNM_NOMATCH);
255 ptmp = p;
256 stmp = s;
257 continue;
259 case '?':
260 if (ISEND(s))
261 RETURN(FNM_NOMATCH);
262 p++;
263 Inc(s);
264 continue;
266 case '[': {
267 const char *t;
268 if (ISEND(s))
269 RETURN(FNM_NOMATCH);
270 if ((t = bracket(p + 1, s, flags)) != 0) {
271 p = t;
272 Inc(s);
273 continue;
275 goto failed;
279 /* ordinary */
280 p = UNESCAPE(p);
281 if (ISEND(s))
282 RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
283 if (ISEND(p))
284 goto failed;
285 if (Compare(p, s) != 0)
286 goto failed;
287 Inc(p);
288 Inc(s);
289 continue;
291 failed: /* try next '*' position */
292 if (ptmp && stmp) {
293 p = ptmp;
294 Inc(stmp); /* !ISEND(*stmp) */
295 s = stmp;
296 continue;
298 RETURN(FNM_NOMATCH);
302 static int
303 fnmatch(
304 const char *p, /* pattern */
305 const char *s, /* string */
306 int flags)
308 const int period = !(flags & FNM_DOTMATCH);
309 const int pathname = flags & FNM_PATHNAME;
311 const char *ptmp = 0;
312 const char *stmp = 0;
314 if (pathname) {
315 while (1) {
316 if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
317 do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
318 ptmp = p;
319 stmp = s;
321 if (fnmatch_helper(&p, &s, flags) == 0) {
322 while (*s && *s != '/') Inc(s);
323 if (*p && *s) {
324 p++;
325 s++;
326 continue;
328 if (!*p && !*s)
329 return 0;
331 /* failed : try next recursion */
332 if (ptmp && stmp && !(period && *stmp == '.')) {
333 while (*stmp && *stmp != '/') Inc(stmp);
334 if (*stmp) {
335 p = ptmp;
336 stmp++;
337 s = stmp;
338 continue;
341 return FNM_NOMATCH;
344 else
345 return fnmatch_helper(&p, &s, flags);
348 VALUE rb_cDir;
350 struct dir_data {
351 DIR *dir;
352 char *path;
355 static void
356 free_dir(struct dir_data *dir)
358 if (dir) {
359 if (dir->dir) closedir(dir->dir);
360 if (dir->path) free(dir->path);
362 free(dir);
365 static VALUE dir_close(VALUE);
367 static VALUE
368 dir_s_alloc(VALUE klass)
370 struct dir_data *dirp;
371 VALUE obj = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dirp);
373 dirp->dir = NULL;
374 dirp->path = NULL;
376 return obj;
380 * call-seq:
381 * Dir.new( string ) -> aDir
383 * Returns a new directory object for the named directory.
385 static VALUE
386 dir_initialize(VALUE dir, VALUE dirname)
388 struct dir_data *dp;
390 FilePathValue(dirname);
391 Data_Get_Struct(dir, struct dir_data, dp);
392 if (dp->dir) closedir(dp->dir);
393 if (dp->path) free(dp->path);
394 dp->dir = NULL;
395 dp->path = NULL;
396 dp->dir = opendir(RSTRING_PTR(dirname));
397 if (dp->dir == NULL) {
398 if (errno == EMFILE || errno == ENFILE) {
399 rb_gc();
400 dp->dir = opendir(RSTRING_PTR(dirname));
402 if (dp->dir == NULL) {
403 rb_sys_fail(RSTRING_PTR(dirname));
406 dp->path = strdup(RSTRING_PTR(dirname));
408 return dir;
412 * call-seq:
413 * Dir.open( string ) => aDir
414 * Dir.open( string ) {| aDir | block } => anObject
416 * With no block, <code>open</code> is a synonym for
417 * <code>Dir::new</code>. If a block is present, it is passed
418 * <i>aDir</i> as a parameter. The directory is closed at the end of
419 * the block, and <code>Dir::open</code> returns the value of the
420 * block.
422 static VALUE
423 dir_s_open(VALUE klass, VALUE dirname)
425 struct dir_data *dp;
426 VALUE dir = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dp);
428 dir_initialize(dir, dirname);
429 if (rb_block_given_p()) {
430 return rb_ensure(rb_yield, dir, dir_close, dir);
433 return dir;
436 static void
437 dir_closed(void)
439 rb_raise(rb_eIOError, "closed directory");
442 static void
443 dir_check(VALUE dir)
445 if (!OBJ_TAINTED(dir) && rb_safe_level() >= 4)
446 rb_raise(rb_eSecurityError, "Insecure: operation on untainted Dir");
447 rb_check_frozen(dir);
450 #define GetDIR(obj, dirp) do {\
451 dir_check(dir);\
452 Data_Get_Struct(obj, struct dir_data, dirp);\
453 if (dirp->dir == NULL) dir_closed();\
454 } while (0)
457 * call-seq:
458 * dir.inspect => string
460 * Return a string describing this Dir object.
462 static VALUE
463 dir_inspect(VALUE dir)
465 struct dir_data *dirp;
467 Data_Get_Struct(dir, struct dir_data, dirp);
468 if (dirp->path) {
469 char *c = rb_obj_classname(dir);
470 int len = strlen(c) + strlen(dirp->path) + 4;
471 VALUE s = rb_str_new(0, len);
472 snprintf(RSTRING_PTR(s), len+1, "#<%s:%s>", c, dirp->path);
473 return s;
475 return rb_funcall(dir, rb_intern("to_s"), 0, 0);
479 * call-seq:
480 * dir.path => string or nil
482 * Returns the path parameter passed to <em>dir</em>'s constructor.
484 * d = Dir.new("..")
485 * d.path #=> ".."
487 static VALUE
488 dir_path(VALUE dir)
490 struct dir_data *dirp;
492 Data_Get_Struct(dir, struct dir_data, dirp);
493 if (!dirp->path) return Qnil;
494 return rb_str_new2(dirp->path);
498 * call-seq:
499 * dir.read => string or nil
501 * Reads the next entry from <em>dir</em> and returns it as a string.
502 * Returns <code>nil</code> at the end of the stream.
504 * d = Dir.new("testdir")
505 * d.read #=> "."
506 * d.read #=> ".."
507 * d.read #=> "config.h"
509 static VALUE
510 dir_read(VALUE dir)
512 struct dir_data *dirp;
513 struct dirent *dp;
515 GetDIR(dir, dirp);
516 errno = 0;
517 dp = readdir(dirp->dir);
518 if (dp) {
519 return rb_tainted_str_new(dp->d_name, NAMLEN(dp));
521 else if (errno == 0) { /* end of stream */
522 return Qnil;
524 else {
525 rb_sys_fail(0);
527 return Qnil; /* not reached */
531 * call-seq:
532 * dir.each { |filename| block } => dir
534 * Calls the block once for each entry in this directory, passing the
535 * filename of each entry as a parameter to the block.
537 * d = Dir.new("testdir")
538 * d.each {|x| puts "Got #{x}" }
540 * <em>produces:</em>
542 * Got .
543 * Got ..
544 * Got config.h
545 * Got main.rb
547 static VALUE
548 dir_each(VALUE dir)
550 struct dir_data *dirp;
551 struct dirent *dp;
553 RETURN_ENUMERATOR(dir, 0, 0);
554 GetDIR(dir, dirp);
555 rewinddir(dirp->dir);
556 for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) {
557 rb_yield(rb_tainted_str_new(dp->d_name, NAMLEN(dp)));
558 if (dirp->dir == NULL) dir_closed();
560 return dir;
564 * call-seq:
565 * dir.pos => integer
566 * dir.tell => integer
568 * Returns the current position in <em>dir</em>. See also
569 * <code>Dir#seek</code>.
571 * d = Dir.new("testdir")
572 * d.tell #=> 0
573 * d.read #=> "."
574 * d.tell #=> 12
576 static VALUE
577 dir_tell(VALUE dir)
579 #ifdef HAVE_TELLDIR
580 struct dir_data *dirp;
581 long pos;
583 GetDIR(dir, dirp);
584 pos = telldir(dirp->dir);
585 return rb_int2inum(pos);
586 #else
587 rb_notimplement();
588 #endif
592 * call-seq:
593 * dir.seek( integer ) => dir
595 * Seeks to a particular location in <em>dir</em>. <i>integer</i>
596 * must be a value returned by <code>Dir#tell</code>.
598 * d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
599 * d.read #=> "."
600 * i = d.tell #=> 12
601 * d.read #=> ".."
602 * d.seek(i) #=> #<Dir:0x401b3c40>
603 * d.read #=> ".."
605 static VALUE
606 dir_seek(VALUE dir, VALUE pos)
608 struct dir_data *dirp;
609 off_t p = NUM2OFFT(pos);
611 GetDIR(dir, dirp);
612 #ifdef HAVE_SEEKDIR
613 seekdir(dirp->dir, p);
614 return dir;
615 #else
616 rb_notimplement();
617 #endif
621 * call-seq:
622 * dir.pos( integer ) => integer
624 * Synonym for <code>Dir#seek</code>, but returns the position
625 * parameter.
627 * d = Dir.new("testdir") #=> #<Dir:0x401b3c40>
628 * d.read #=> "."
629 * i = d.pos #=> 12
630 * d.read #=> ".."
631 * d.pos = i #=> 12
632 * d.read #=> ".."
634 static VALUE
635 dir_set_pos(VALUE dir, VALUE pos)
637 dir_seek(dir, pos);
638 return pos;
642 * call-seq:
643 * dir.rewind => dir
645 * Repositions <em>dir</em> to the first entry.
647 * d = Dir.new("testdir")
648 * d.read #=> "."
649 * d.rewind #=> #<Dir:0x401b3fb0>
650 * d.read #=> "."
652 static VALUE
653 dir_rewind(VALUE dir)
655 struct dir_data *dirp;
657 if (rb_safe_level() >= 4 && !OBJ_TAINTED(dir)) {
658 rb_raise(rb_eSecurityError, "Insecure: can't close");
660 GetDIR(dir, dirp);
661 rewinddir(dirp->dir);
662 return dir;
666 * call-seq:
667 * dir.close => nil
669 * Closes the directory stream. Any further attempts to access
670 * <em>dir</em> will raise an <code>IOError</code>.
672 * d = Dir.new("testdir")
673 * d.close #=> nil
675 static VALUE
676 dir_close(VALUE dir)
678 struct dir_data *dirp;
680 GetDIR(dir, dirp);
681 closedir(dirp->dir);
682 dirp->dir = NULL;
684 return Qnil;
687 static void
688 dir_chdir(VALUE path)
690 if (chdir(RSTRING_PTR(path)) < 0)
691 rb_sys_fail(RSTRING_PTR(path));
694 static int chdir_blocking = 0;
695 static VALUE chdir_thread = Qnil;
697 struct chdir_data {
698 VALUE old_path, new_path;
699 int done;
702 static VALUE
703 chdir_yield(struct chdir_data *args)
705 dir_chdir(args->new_path);
706 args->done = Qtrue;
707 chdir_blocking++;
708 if (chdir_thread == Qnil)
709 chdir_thread = rb_thread_current();
710 return rb_yield(args->new_path);
713 static VALUE
714 chdir_restore(struct chdir_data *args)
716 if (args->done) {
717 chdir_blocking--;
718 if (chdir_blocking == 0)
719 chdir_thread = Qnil;
720 dir_chdir(args->old_path);
722 return Qnil;
726 * call-seq:
727 * Dir.chdir( [ string] ) => 0
728 * Dir.chdir( [ string] ) {| path | block } => anObject
730 * Changes the current working directory of the process to the given
731 * string. When called without an argument, changes the directory to
732 * the value of the environment variable <code>HOME</code>, or
733 * <code>LOGDIR</code>. <code>SystemCallError</code> (probably
734 * <code>Errno::ENOENT</code>) if the target directory does not exist.
736 * If a block is given, it is passed the name of the new current
737 * directory, and the block is executed with that as the current
738 * directory. The original working directory is restored when the block
739 * exits. The return value of <code>chdir</code> is the value of the
740 * block. <code>chdir</code> blocks can be nested, but in a
741 * multi-threaded program an error will be raised if a thread attempts
742 * to open a <code>chdir</code> block while another thread has one
743 * open.
745 * Dir.chdir("/var/spool/mail")
746 * puts Dir.pwd
747 * Dir.chdir("/tmp") do
748 * puts Dir.pwd
749 * Dir.chdir("/usr") do
750 * puts Dir.pwd
751 * end
752 * puts Dir.pwd
753 * end
754 * puts Dir.pwd
756 * <em>produces:</em>
758 * /var/spool/mail
759 * /tmp
760 * /usr
761 * /tmp
762 * /var/spool/mail
764 static VALUE
765 dir_s_chdir(int argc, VALUE *argv, VALUE obj)
767 VALUE path = Qnil;
769 rb_secure(2);
770 if (rb_scan_args(argc, argv, "01", &path) == 1) {
771 FilePathValue(path);
773 else {
774 const char *dist = getenv("HOME");
775 if (!dist) {
776 dist = getenv("LOGDIR");
777 if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
779 path = rb_str_new2(dist);
782 if (chdir_blocking > 0) {
783 if (!rb_block_given_p() || rb_thread_current() != chdir_thread)
784 rb_warn("conflicting chdir during another chdir block");
787 if (rb_block_given_p()) {
788 struct chdir_data args;
789 char *cwd = my_getcwd();
791 args.old_path = rb_tainted_str_new2(cwd); free(cwd);
792 args.new_path = path;
793 args.done = Qfalse;
794 return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args);
796 dir_chdir(path);
798 return INT2FIX(0);
802 * call-seq:
803 * Dir.getwd => string
804 * Dir.pwd => string
806 * Returns the path to the current working directory of this process as
807 * a string.
809 * Dir.chdir("/tmp") #=> 0
810 * Dir.getwd #=> "/tmp"
812 static VALUE
813 dir_s_getwd(VALUE dir)
815 char *path;
816 VALUE cwd;
818 rb_secure(4);
819 path = my_getcwd();
820 cwd = rb_tainted_str_new2(path);
822 free(path);
823 return cwd;
826 static void
827 check_dirname(volatile VALUE *dir)
829 char *path, *pend;
831 rb_secure(2);
832 FilePathValue(*dir);
833 path = RSTRING_PTR(*dir);
834 if (path && *(pend = rb_path_end(rb_path_skip_prefix(path)))) {
835 *dir = rb_str_new(path, pend - path);
840 * call-seq:
841 * Dir.chroot( string ) => 0
843 * Changes this process's idea of the file system root. Only a
844 * privileged process may make this call. Not available on all
845 * platforms. On Unix systems, see <code>chroot(2)</code> for more
846 * information.
848 static VALUE
849 dir_s_chroot(VALUE dir, VALUE path)
851 #if defined(HAVE_CHROOT) && !defined(__CHECKER__)
852 check_dirname(&path);
854 if (chroot(RSTRING_PTR(path)) == -1)
855 rb_sys_fail(RSTRING_PTR(path));
857 return INT2FIX(0);
858 #else
859 rb_notimplement();
860 return Qnil; /* not reached */
861 #endif
865 * call-seq:
866 * Dir.mkdir( string [, integer] ) => 0
868 * Makes a new directory named by <i>string</i>, with permissions
869 * specified by the optional parameter <i>anInteger</i>. The
870 * permissions may be modified by the value of
871 * <code>File::umask</code>, and are ignored on NT. Raises a
872 * <code>SystemCallError</code> if the directory cannot be created. See
873 * also the discussion of permissions in the class documentation for
874 * <code>File</code>.
877 static VALUE
878 dir_s_mkdir(int argc, VALUE *argv, VALUE obj)
880 VALUE path, vmode;
881 int mode;
883 if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
884 mode = NUM2INT(vmode);
886 else {
887 mode = 0777;
890 check_dirname(&path);
891 if (mkdir(RSTRING_PTR(path), mode) == -1)
892 rb_sys_fail(RSTRING_PTR(path));
894 return INT2FIX(0);
898 * call-seq:
899 * Dir.delete( string ) => 0
900 * Dir.rmdir( string ) => 0
901 * Dir.unlink( string ) => 0
903 * Deletes the named directory. Raises a subclass of
904 * <code>SystemCallError</code> if the directory isn't empty.
906 static VALUE
907 dir_s_rmdir(VALUE obj, VALUE dir)
909 check_dirname(&dir);
910 if (rmdir(RSTRING_PTR(dir)) < 0)
911 rb_sys_fail(RSTRING_PTR(dir));
913 return INT2FIX(0);
916 static void
917 sys_warning_1(const char* mesg)
919 rb_sys_warning("%s", mesg);
922 #define GLOB_VERBOSE (1UL << (sizeof(int) * CHAR_BIT - 1))
923 #define sys_warning(val) \
924 (void)((flags & GLOB_VERBOSE) && rb_protect((VALUE (*)(VALUE))sys_warning_1, (VALUE)(val), 0))
926 #define GLOB_ALLOC(type) (type *)malloc(sizeof(type))
927 #define GLOB_ALLOC_N(type, n) (type *)malloc(sizeof(type) * (n))
928 #define GLOB_JUMP_TAG(status) ((status == -1) ? rb_memerror() : rb_jump_tag(status))
931 * ENOTDIR can be returned by stat(2) if a non-leaf element of the path
932 * is not a directory.
934 #define to_be_ignored(e) ((e) == ENOENT || (e) == ENOTDIR)
936 /* System call with warning */
937 static int
938 do_stat(const char *path, struct stat *pst, int flags)
941 int ret = stat(path, pst);
942 if (ret < 0 && !to_be_ignored(errno))
943 sys_warning(path);
945 return ret;
948 static int
949 do_lstat(const char *path, struct stat *pst, int flags)
951 int ret = lstat(path, pst);
952 if (ret < 0 && !to_be_ignored(errno))
953 sys_warning(path);
955 return ret;
958 static DIR *
959 do_opendir(const char *path, int flags)
961 DIR *dirp = opendir(path);
962 if (dirp == NULL && !to_be_ignored(errno))
963 sys_warning(path);
965 return dirp;
968 /* Return nonzero if S has any special globbing chars in it. */
969 static int
970 has_magic(const char *s, int flags)
972 const int escape = !(flags & FNM_NOESCAPE);
973 const int nocase = flags & FNM_CASEFOLD;
975 register const char *p = s;
976 register char c;
978 while ((c = *p++) != 0) {
979 switch (c) {
980 case '*':
981 case '?':
982 case '[':
983 return 1;
985 case '\\':
986 if (escape && !(c = *p++))
987 return 0;
988 continue;
990 default:
991 if (!FNM_SYSCASE && ISALPHA(c) && nocase)
992 return 1;
995 p = Next(p-1);
998 return 0;
1001 /* Find separator in globbing pattern. */
1002 static char *
1003 find_dirsep(const char *s, int flags)
1005 const int escape = !(flags & FNM_NOESCAPE);
1007 register const char *p = s;
1008 register char c;
1009 int open = 0;
1011 while ((c = *p++) != 0) {
1012 switch (c) {
1013 case '[':
1014 open = 1;
1015 continue;
1016 case ']':
1017 open = 0;
1018 continue;
1020 case '/':
1021 if (!open)
1022 return (char *)p-1;
1023 continue;
1025 case '\\':
1026 if (escape && !(c = *p++))
1027 return (char *)p-1;
1028 continue;
1031 p = Next(p-1);
1034 return (char *)p-1;
1037 /* Remove escaping backslashes */
1038 static void
1039 remove_backslashes(char *p)
1041 char *t = p;
1042 char *s = p;
1044 while (*p) {
1045 if (*p == '\\') {
1046 if (t != s)
1047 memmove(t, s, p - s);
1048 t += p - s;
1049 s = ++p;
1050 if (!*p) break;
1052 Inc(p);
1055 while (*p++);
1057 if (t != s)
1058 memmove(t, s, p - s); /* move '\0' too */
1061 /* Globing pattern */
1062 enum glob_pattern_type { PLAIN, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR };
1064 struct glob_pattern {
1065 char *str;
1066 enum glob_pattern_type type;
1067 struct glob_pattern *next;
1070 static void glob_free_pattern(struct glob_pattern *list);
1072 static struct glob_pattern *
1073 glob_make_pattern(const char *p, int flags)
1075 struct glob_pattern *list, *tmp, **tail = &list;
1076 int dirsep = 0; /* pattern is terminated with '/' */
1078 while (*p) {
1079 tmp = GLOB_ALLOC(struct glob_pattern);
1080 if (!tmp) goto error;
1081 if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
1082 /* fold continuous RECURSIVEs (needed in glob_helper) */
1083 do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
1084 tmp->type = RECURSIVE;
1085 tmp->str = 0;
1086 dirsep = 1;
1088 else {
1089 const char *m = find_dirsep(p, flags);
1090 char *buf = GLOB_ALLOC_N(char, m-p+1);
1091 if (!buf) {
1092 free(tmp);
1093 goto error;
1095 memcpy(buf, p, m-p);
1096 buf[m-p] = '\0';
1097 tmp->type = has_magic(buf, flags) ? MAGICAL : PLAIN;
1098 tmp->str = buf;
1099 if (*m) {
1100 dirsep = 1;
1101 p = m + 1;
1103 else {
1104 dirsep = 0;
1105 p = m;
1108 *tail = tmp;
1109 tail = &tmp->next;
1112 tmp = GLOB_ALLOC(struct glob_pattern);
1113 if (!tmp) {
1114 error:
1115 *tail = 0;
1116 glob_free_pattern(list);
1117 return 0;
1119 tmp->type = dirsep ? MATCH_DIR : MATCH_ALL;
1120 tmp->str = 0;
1121 *tail = tmp;
1122 tmp->next = 0;
1124 return list;
1127 static void
1128 glob_free_pattern(struct glob_pattern *list)
1130 while (list) {
1131 struct glob_pattern *tmp = list;
1132 list = list->next;
1133 if (tmp->str)
1134 free(tmp->str);
1135 free(tmp);
1139 static char *
1140 join_path(const char *path, int dirsep, const char *name)
1142 long len = strlen(path);
1143 char *buf = GLOB_ALLOC_N(char, len+strlen(name)+(dirsep?1:0)+1);
1145 if (!buf) return 0;
1146 memcpy(buf, path, len);
1147 if (dirsep) {
1148 strcpy(buf+len, "/");
1149 len++;
1151 strcpy(buf+len, name);
1152 return buf;
1155 enum answer { YES, NO, UNKNOWN };
1157 #ifndef S_ISDIR
1158 # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
1159 #endif
1161 #ifndef S_ISLNK
1162 # ifndef S_IFLNK
1163 # define S_ISLNK(m) (0)
1164 # else
1165 # define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
1166 # endif
1167 #endif
1169 struct glob_args {
1170 void (*func)(const char *, VALUE);
1171 const char *path;
1172 VALUE value;
1175 static VALUE
1176 glob_func_caller(VALUE val)
1178 struct glob_args *args = (struct glob_args *)val;
1180 (*args->func)(args->path, args->value);
1181 return Qnil;
1184 #define glob_call_func(func, path, arg) (*func)(path, arg)
1186 static int
1187 glob_helper(
1188 const char *path,
1189 int dirsep, /* '/' should be placed before appending child entry's name to 'path'. */
1190 enum answer exist, /* Does 'path' indicate an existing entry? */
1191 enum answer isdir, /* Does 'path' indicate a directory or a symlink to a directory? */
1192 struct glob_pattern **beg,
1193 struct glob_pattern **end,
1194 int flags,
1195 ruby_glob_func *func,
1196 VALUE arg)
1198 struct stat st;
1199 int status = 0;
1200 struct glob_pattern **cur, **new_beg, **new_end;
1201 int plain = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0;
1202 int escape = !(flags & FNM_NOESCAPE);
1204 for (cur = beg; cur < end; ++cur) {
1205 struct glob_pattern *p = *cur;
1206 if (p->type == RECURSIVE) {
1207 recursive = 1;
1208 p = p->next;
1210 switch (p->type) {
1211 case PLAIN:
1212 plain = 1;
1213 break;
1214 case MAGICAL:
1215 magical = 1;
1216 break;
1217 case MATCH_ALL:
1218 match_all = 1;
1219 break;
1220 case MATCH_DIR:
1221 match_dir = 1;
1222 break;
1223 case RECURSIVE:
1224 rb_bug("continuous RECURSIVEs");
1228 if (*path) {
1229 if (match_all && exist == UNKNOWN) {
1230 if (do_lstat(path, &st, flags) == 0) {
1231 exist = YES;
1232 isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO;
1234 else {
1235 exist = NO;
1236 isdir = NO;
1239 if (match_dir && isdir == UNKNOWN) {
1240 if (do_stat(path, &st, flags) == 0) {
1241 exist = YES;
1242 isdir = S_ISDIR(st.st_mode) ? YES : NO;
1244 else {
1245 exist = NO;
1246 isdir = NO;
1249 if (match_all && exist == YES) {
1250 status = glob_call_func(func, path, arg);
1251 if (status) return status;
1253 if (match_dir && isdir == YES) {
1254 char *tmp = join_path(path, dirsep, "");
1255 if (!tmp) return -1;
1256 status = glob_call_func(func, tmp, arg);
1257 free(tmp);
1258 if (status) return status;
1262 if (exist == NO || isdir == NO) return 0;
1264 if (magical || recursive) {
1265 struct dirent *dp;
1266 DIR *dirp = do_opendir(*path ? path : ".", flags);
1267 if (dirp == NULL) return 0;
1269 for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
1270 char *buf = join_path(path, dirsep, dp->d_name);
1271 enum answer new_isdir = UNKNOWN;
1273 if (!buf) {
1274 status = -1;
1275 break;
1277 if (recursive && strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0
1278 && fnmatch("*", dp->d_name, flags) == 0) {
1279 #ifndef _WIN32
1280 if (do_lstat(buf, &st, flags) == 0)
1281 new_isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO;
1282 else
1283 new_isdir = NO;
1284 #else
1285 new_isdir = dp->d_isdir ? (!dp->d_isrep ? YES : UNKNOWN) : NO;
1286 #endif
1289 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2);
1290 if (!new_beg) {
1291 status = -1;
1292 break;
1295 for (cur = beg; cur < end; ++cur) {
1296 struct glob_pattern *p = *cur;
1297 if (p->type == RECURSIVE) {
1298 if (new_isdir == YES) /* not symlink but real directory */
1299 *new_end++ = p; /* append recursive pattern */
1300 p = p->next; /* 0 times recursion */
1302 if (p->type == PLAIN || p->type == MAGICAL) {
1303 if (fnmatch(p->str, dp->d_name, flags) == 0)
1304 *new_end++ = p->next;
1308 status = glob_helper(buf, 1, YES, new_isdir, new_beg, new_end, flags, func, arg);
1309 free(buf);
1310 free(new_beg);
1311 if (status) break;
1314 closedir(dirp);
1316 else if (plain) {
1317 struct glob_pattern **copy_beg, **copy_end, **cur2;
1319 copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
1320 if (!copy_beg) return -1;
1321 for (cur = beg; cur < end; ++cur)
1322 *copy_end++ = (*cur)->type == PLAIN ? *cur : 0;
1324 for (cur = copy_beg; cur < copy_end; ++cur) {
1325 if (*cur) {
1326 char *buf;
1327 char *name;
1328 name = GLOB_ALLOC_N(char, strlen((*cur)->str) + 1);
1329 if (!name) {
1330 status = -1;
1331 break;
1333 strcpy(name, (*cur)->str);
1334 if (escape) remove_backslashes(name);
1336 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
1337 if (!new_beg) {
1338 free(name);
1339 status = -1;
1340 break;
1342 *new_end++ = (*cur)->next;
1343 for (cur2 = cur + 1; cur2 < copy_end; ++cur2) {
1344 if (*cur2 && fnmatch((*cur2)->str, name, flags) == 0) {
1345 *new_end++ = (*cur2)->next;
1346 *cur2 = 0;
1350 buf = join_path(path, dirsep, name);
1351 free(name);
1352 if (!buf) {
1353 free(new_beg);
1354 status = -1;
1355 break;
1357 status = glob_helper(buf, 1, UNKNOWN, UNKNOWN, new_beg, new_end, flags, func, arg);
1358 free(buf);
1359 free(new_beg);
1360 if (status) break;
1364 free(copy_beg);
1367 return status;
1370 static int
1371 ruby_glob0(const char *path, int flags, ruby_glob_func *func, VALUE arg)
1373 struct glob_pattern *list;
1374 const char *root, *start;
1375 char *buf;
1376 int n;
1377 int status;
1379 start = root = path;
1380 flags |= FNM_SYSCASE;
1381 #if defined DOSISH
1382 root = rb_path_skip_prefix(root);
1383 #endif
1385 if (root && *root == '/') root++;
1387 n = root - start;
1388 buf = GLOB_ALLOC_N(char, n + 1);
1389 if (!buf) return -1;
1390 MEMCPY(buf, start, char, n);
1391 buf[n] = '\0';
1393 list = glob_make_pattern(root, flags);
1394 if (!list) {
1395 free(buf);
1396 return -1;
1398 status = glob_helper(buf, 0, UNKNOWN, UNKNOWN, &list, &list + 1, flags, func, arg);
1399 glob_free_pattern(list);
1400 free(buf);
1402 return status;
1406 ruby_glob(const char *path, int flags, ruby_glob_func *func, VALUE arg)
1408 return ruby_glob0(path, flags & ~GLOB_VERBOSE, func, arg);
1411 static int
1412 rb_glob_caller(const char *path, VALUE a)
1414 int status;
1415 struct glob_args *args = (struct glob_args *)a;
1417 args->path = path;
1418 rb_protect(glob_func_caller, a, &status);
1419 return status;
1422 static int
1423 rb_glob2(const char *path, int flags, void (*func)(const char *, VALUE), VALUE arg)
1425 struct glob_args args;
1427 args.func = func;
1428 args.value = arg;
1430 if (flags & FNM_SYSCASE) {
1431 rb_warning("Dir.glob() ignores File::FNM_CASEFOLD");
1434 return ruby_glob0(path, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args);
1437 void
1438 rb_glob(const char *path, void (*func)(const char *, VALUE), VALUE arg)
1440 int status = rb_glob2(path, 0, func, arg);
1441 if (status) GLOB_JUMP_TAG(status);
1444 static void
1445 push_pattern(const char *path, VALUE ary)
1447 rb_ary_push(ary, rb_tainted_str_new2(path));
1451 ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg)
1453 const int escape = !(flags & FNM_NOESCAPE);
1454 const char *p = str;
1455 const char *s = p;
1456 const char *lbrace = 0, *rbrace = 0;
1457 int nest = 0, status = 0;
1459 while (*p) {
1460 if (*p == '{' && nest++ == 0) {
1461 lbrace = p;
1463 if (*p == '}' && --nest <= 0) {
1464 rbrace = p;
1465 break;
1467 if (*p == '\\' && escape) {
1468 if (!*++p) break;
1470 Inc(p);
1473 if (lbrace && rbrace) {
1474 char *buf = GLOB_ALLOC_N(char, strlen(s) + 1);
1475 long shift;
1477 if (!buf) return -1;
1478 memcpy(buf, s, lbrace-s);
1479 shift = (lbrace-s);
1480 p = lbrace;
1481 while (p < rbrace) {
1482 const char *t = ++p;
1483 nest = 0;
1484 while (p < rbrace && !(*p == ',' && nest == 0)) {
1485 if (*p == '{') nest++;
1486 if (*p == '}') nest--;
1487 if (*p == '\\' && escape) {
1488 if (++p == rbrace) break;
1490 Inc(p);
1492 memcpy(buf+shift, t, p-t);
1493 strcpy(buf+shift+(p-t), rbrace+1);
1494 status = ruby_brace_expand(buf, flags, func, arg);
1495 if (status) break;
1497 free(buf);
1499 else if (!lbrace && !rbrace) {
1500 status = (*func)(s, arg);
1503 return status;
1506 struct brace_args {
1507 ruby_glob_func *func;
1508 VALUE value;
1509 int flags;
1512 static int
1513 glob_brace(const char *path, VALUE val)
1515 struct brace_args *arg = (struct brace_args *)val;
1517 return ruby_glob0(path, arg->flags, arg->func, arg->value);
1520 static int
1521 ruby_brace_glob0(const char *str, int flags, ruby_glob_func *func, VALUE arg)
1523 struct brace_args args;
1525 args.func = func;
1526 args.value = arg;
1527 args.flags = flags;
1528 return ruby_brace_expand(str, flags, glob_brace, (VALUE)&args);
1532 ruby_brace_glob(const char *str, int flags, ruby_glob_func *func, VALUE arg)
1534 return ruby_brace_glob0(str, flags & ~GLOB_VERBOSE, func, arg);
1537 static int
1538 push_glob(VALUE ary, const char *str, int flags)
1540 struct glob_args args;
1542 args.func = push_pattern;
1543 args.value = ary;
1544 return ruby_brace_glob0(str, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args);
1547 static VALUE
1548 rb_push_glob(VALUE str, int flags) /* '\0' is delimiter */
1550 long offset = 0;
1551 VALUE ary;
1553 StringValue(str);
1554 ary = rb_ary_new();
1556 while (offset < RSTRING_LEN(str)) {
1557 int status = push_glob(ary, RSTRING_PTR(str) + offset, flags);
1558 char *p, *pend;
1559 if (status) GLOB_JUMP_TAG(status);
1560 if (offset >= RSTRING_LEN(str)) break;
1561 p = RSTRING_PTR(str) + offset;
1562 p += strlen(p) + 1;
1563 pend = RSTRING_PTR(str) + RSTRING_LEN(str);
1564 while (p < pend && !*p)
1565 p++;
1566 offset = p - RSTRING_PTR(str);
1569 return ary;
1572 static VALUE
1573 dir_globs(long argc, VALUE *argv, int flags)
1575 VALUE ary = rb_ary_new();
1576 long i;
1578 for (i = 0; i < argc; ++i) {
1579 int status;
1580 VALUE str = argv[i];
1581 StringValue(str);
1582 status = push_glob(ary, RSTRING_PTR(str), flags);
1583 if (status) GLOB_JUMP_TAG(status);
1586 return ary;
1590 * call-seq:
1591 * Dir[ array ] => array
1592 * Dir[ string [, string ...] ] => array
1594 * Equivalent to calling
1595 * <code>Dir.glob(</code><i>array,</i><code>0)</code> and
1596 * <code>Dir.glob([</code><i>string,...</i><code>],0)</code>.
1599 static VALUE
1600 dir_s_aref(int argc, VALUE *argv, VALUE obj)
1602 if (argc == 1) {
1603 return rb_push_glob(argv[0], 0);
1605 return dir_globs(argc, argv, 0);
1609 * call-seq:
1610 * Dir.glob( pattern, [flags] ) => array
1611 * Dir.glob( pattern, [flags] ) {| filename | block } => nil
1613 * Returns the filenames found by expanding <i>pattern</i> which is
1614 * an +Array+ of the patterns or the pattern +String+, either as an
1615 * <i>array</i> or as parameters to the block. Note that this pattern
1616 * is not a regexp (it's closer to a shell glob). See
1617 * <code>File::fnmatch</code> for the meaning of the <i>flags</i>
1618 * parameter. Note that case sensitivity depends on your system (so
1619 * <code>File::FNM_CASEFOLD</code> is ignored)
1621 * <code>*</code>:: Matches any file. Can be restricted by
1622 * other values in the glob. <code>*</code>
1623 * will match all files; <code>c*</code> will
1624 * match all files beginning with
1625 * <code>c</code>; <code>*c</code> will match
1626 * all files ending with <code>c</code>; and
1627 * <code>*c*</code> will match all files that
1628 * have <code>c</code> in them (including at
1629 * the beginning or end). Equivalent to
1630 * <code>/ .* /x</code> in regexp.
1631 * <code>**</code>:: Matches directories recursively.
1632 * <code>?</code>:: Matches any one character. Equivalent to
1633 * <code>/.{1}/</code> in regexp.
1634 * <code>[set]</code>:: Matches any one character in +set+.
1635 * Behaves exactly like character sets in
1636 * Regexp, including set negation
1637 * (<code>[^a-z]</code>).
1638 * <code>{p,q}</code>:: Matches either literal <code>p</code> or
1639 * literal <code>q</code>. Matching literals
1640 * may be more than one character in length.
1641 * More than two literals may be specified.
1642 * Equivalent to pattern alternation in
1643 * regexp.
1644 * <code>\</code>:: Escapes the next metacharacter.
1646 * Dir["config.?"] #=> ["config.h"]
1647 * Dir.glob("config.?") #=> ["config.h"]
1648 * Dir.glob("*.[a-z][a-z]") #=> ["main.rb"]
1649 * Dir.glob("*.[^r]*") #=> ["config.h"]
1650 * Dir.glob("*.{rb,h}") #=> ["main.rb", "config.h"]
1651 * Dir.glob("*") #=> ["config.h", "main.rb"]
1652 * Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "..", "config.h", "main.rb"]
1654 * rbfiles = File.join("**", "*.rb")
1655 * Dir.glob(rbfiles) #=> ["main.rb",
1656 * # "lib/song.rb",
1657 * # "lib/song/karaoke.rb"]
1658 * libdirs = File.join("**", "lib")
1659 * Dir.glob(libdirs) #=> ["lib"]
1661 * librbfiles = File.join("**", "lib", "**", "*.rb")
1662 * Dir.glob(librbfiles) #=> ["lib/song.rb",
1663 * # "lib/song/karaoke.rb"]
1665 * librbfiles = File.join("**", "lib", "*.rb")
1666 * Dir.glob(librbfiles) #=> ["lib/song.rb"]
1668 static VALUE
1669 dir_s_glob(int argc, VALUE *argv, VALUE obj)
1671 VALUE str, rflags, ary;
1672 int flags;
1674 if (rb_scan_args(argc, argv, "11", &str, &rflags) == 2)
1675 flags = NUM2INT(rflags);
1676 else
1677 flags = 0;
1679 ary = rb_check_array_type(str);
1680 if (NIL_P(ary)) {
1681 ary = rb_push_glob(str, flags);
1683 else {
1684 volatile VALUE v = ary;
1685 ary = dir_globs(RARRAY_LEN(v), RARRAY_PTR(v), flags);
1688 if (rb_block_given_p()) {
1689 rb_ary_each(ary);
1690 return Qnil;
1692 return ary;
1695 static VALUE
1696 dir_open_dir(VALUE path)
1698 VALUE dir = rb_funcall(rb_cDir, rb_intern("open"), 1, path);
1700 if (TYPE(dir) != T_DATA ||
1701 RDATA(dir)->dfree != (RUBY_DATA_FUNC)free_dir) {
1702 rb_raise(rb_eTypeError, "wrong argument type %s (expected Dir)",
1703 rb_obj_classname(dir));
1705 return dir;
1710 * call-seq:
1711 * Dir.foreach( dirname ) {| filename | block } => nil
1713 * Calls the block once for each entry in the named directory, passing
1714 * the filename of each entry as a parameter to the block.
1716 * Dir.foreach("testdir") {|x| puts "Got #{x}" }
1718 * <em>produces:</em>
1720 * Got .
1721 * Got ..
1722 * Got config.h
1723 * Got main.rb
1726 static VALUE
1727 dir_foreach(VALUE io, VALUE dirname)
1729 VALUE dir;
1731 RETURN_ENUMERATOR(io, 1, &dirname);
1732 dir = dir_open_dir(dirname);
1733 rb_ensure(dir_each, dir, dir_close, dir);
1734 return Qnil;
1738 * call-seq:
1739 * Dir.entries( dirname ) => array
1741 * Returns an array containing all of the filenames in the given
1742 * directory. Will raise a <code>SystemCallError</code> if the named
1743 * directory doesn't exist.
1745 * Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"]
1748 static VALUE
1749 dir_entries(VALUE io, VALUE dirname)
1751 VALUE dir;
1753 dir = dir_open_dir(dirname);
1754 return rb_ensure(rb_Array, dir, dir_close, dir);
1758 * call-seq:
1759 * File.fnmatch( pattern, path, [flags] ) => (true or false)
1760 * File.fnmatch?( pattern, path, [flags] ) => (true or false)
1762 * Returns true if <i>path</i> matches against <i>pattern</i> The
1763 * pattern is not a regular expression; instead it follows rules
1764 * similar to shell filename globbing. It may contain the following
1765 * metacharacters:
1767 * <code>*</code>:: Matches any file. Can be restricted by
1768 * other values in the glob. <code>*</code>
1769 * will match all files; <code>c*</code> will
1770 * match all files beginning with
1771 * <code>c</code>; <code>*c</code> will match
1772 * all files ending with <code>c</code>; and
1773 * <code>*c*</code> will match all files that
1774 * have <code>c</code> in them (including at
1775 * the beginning or end). Equivalent to
1776 * <code>/ .* /x</code> in regexp.
1777 * <code>**</code>:: Matches directories recursively or files
1778 * expansively.
1779 * <code>?</code>:: Matches any one character. Equivalent to
1780 * <code>/.{1}/</code> in regexp.
1781 * <code>[set]</code>:: Matches any one character in +set+.
1782 * Behaves exactly like character sets in
1783 * Regexp, including set negation
1784 * (<code>[^a-z]</code>).
1785 * <code>\</code>:: Escapes the next metacharacter.
1787 * <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
1788 * parameters. The same glob pattern and flags are used by
1789 * <code>Dir::glob</code>.
1791 * File.fnmatch('cat', 'cat') #=> true # match entire string
1792 * File.fnmatch('cat', 'category') #=> false # only match partial string
1793 * File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported
1795 * File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character
1796 * File.fnmatch('c??t', 'cat') #=> false # ditto
1797 * File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters
1798 * File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto
1799 * File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression
1800 * File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!')
1802 * File.fnmatch('cat', 'CAT') #=> false # case sensitive
1803 * File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive
1805 * File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME
1806 * File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto
1807 * File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto
1809 * File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary
1810 * File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary
1811 * File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESACPE makes '\' ordinary
1812 * File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression
1814 * File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading
1815 * File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default.
1816 * File.fnmatch('.*', '.profile') #=> true
1818 * rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
1819 * File.fnmatch(rbfiles, 'main.rb') #=> false
1820 * File.fnmatch(rbfiles, './main.rb') #=> false
1821 * File.fnmatch(rbfiles, 'lib/song.rb') #=> true
1822 * File.fnmatch('**.rb', 'main.rb') #=> true
1823 * File.fnmatch('**.rb', './main.rb') #=> false
1824 * File.fnmatch('**.rb', 'lib/song.rb') #=> true
1825 * File.fnmatch('*', 'dave/.profile') #=> true
1827 * pattern = '*' '/' '*'
1828 * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false
1829 * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
1831 * pattern = '**' '/' 'foo'
1832 * File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true
1833 * File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true
1834 * File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true
1835 * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false
1836 * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
1838 static VALUE
1839 file_s_fnmatch(int argc, VALUE *argv, VALUE obj)
1841 VALUE pattern, path;
1842 VALUE rflags;
1843 int flags;
1845 if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
1846 flags = NUM2INT(rflags);
1847 else
1848 flags = 0;
1850 StringValue(pattern);
1851 FilePathStringValue(path);
1853 if (fnmatch(RSTRING_PTR(pattern), RSTRING_PTR(path), flags) == 0)
1854 return Qtrue;
1856 return Qfalse;
1860 * Objects of class <code>Dir</code> are directory streams representing
1861 * directories in the underlying file system. They provide a variety of
1862 * ways to list directories and their contents. See also
1863 * <code>File</code>.
1865 * The directory used in these examples contains the two regular files
1866 * (<code>config.h</code> and <code>main.rb</code>), the parent
1867 * directory (<code>..</code>), and the directory itself
1868 * (<code>.</code>).
1870 void
1871 Init_Dir(void)
1873 rb_cDir = rb_define_class("Dir", rb_cObject);
1875 rb_include_module(rb_cDir, rb_mEnumerable);
1877 rb_define_alloc_func(rb_cDir, dir_s_alloc);
1878 rb_define_singleton_method(rb_cDir, "open", dir_s_open, 1);
1879 rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, 1);
1880 rb_define_singleton_method(rb_cDir, "entries", dir_entries, 1);
1882 rb_define_method(rb_cDir,"initialize", dir_initialize, 1);
1883 rb_define_method(rb_cDir,"path", dir_path, 0);
1884 rb_define_method(rb_cDir,"inspect", dir_inspect, 0);
1885 rb_define_method(rb_cDir,"read", dir_read, 0);
1886 rb_define_method(rb_cDir,"each", dir_each, 0);
1887 rb_define_method(rb_cDir,"rewind", dir_rewind, 0);
1888 rb_define_method(rb_cDir,"tell", dir_tell, 0);
1889 rb_define_method(rb_cDir,"seek", dir_seek, 1);
1890 rb_define_method(rb_cDir,"pos", dir_tell, 0);
1891 rb_define_method(rb_cDir,"pos=", dir_set_pos, 1);
1892 rb_define_method(rb_cDir,"close", dir_close, 0);
1894 rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1);
1895 rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0);
1896 rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0);
1897 rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1);
1898 rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1);
1899 rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1);
1900 rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1);
1901 rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1);
1903 rb_define_singleton_method(rb_cDir,"glob", dir_s_glob, -1);
1904 rb_define_singleton_method(rb_cDir,"[]", dir_s_aref, -1);
1905 rb_define_singleton_method(rb_cDir,"exist?", rb_file_directory_p, 1); /* in file.c */
1906 rb_define_singleton_method(rb_cDir,"exists?", rb_file_directory_p, 1); /* in file.c */
1908 rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1);
1909 rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1);
1911 rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE));
1912 rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME));
1913 rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH));
1914 rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD));
1915 rb_file_const("FNM_SYSCASE", INT2FIX(FNM_SYSCASE));