[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / file.c
blob835f19e541df97d32ca4c56c5e0b6354a84c29d9
1 /**********************************************************************
3 file.c -
5 $Author$
6 created at: Mon Nov 15 12:24:34 JST 1993
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/internal/config.h"
16 #ifdef _WIN32
17 # include "missing/file.h"
18 # include "ruby.h"
19 #endif
21 #include <ctype.h>
22 #include <time.h>
24 #ifdef __CYGWIN__
25 # include <windows.h>
26 # include <sys/cygwin.h>
27 # include <wchar.h>
28 #endif
30 #ifdef __APPLE__
31 # if !(defined(__has_feature) && defined(__has_attribute))
32 /* Maybe a bug in SDK of Xcode 10.2.1 */
33 /* In this condition, <os/availability.h> does not define
34 * API_AVAILABLE and similar, but __API_AVAILABLE and similar which
35 * are defined in <Availability.h> */
36 # define API_AVAILABLE(...)
37 # define API_DEPRECATED(...)
38 # endif
39 # include <CoreFoundation/CFString.h>
40 #endif
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
50 #ifdef HAVE_SYS_FILE_H
51 # include <sys/file.h>
52 #else
53 int flock(int, int);
54 #endif
56 #ifdef HAVE_SYS_PARAM_H
57 # include <sys/param.h>
58 #endif
59 #ifndef MAXPATHLEN
60 # define MAXPATHLEN 1024
61 #endif
63 #ifdef HAVE_UTIME_H
64 # include <utime.h>
65 #elif defined HAVE_SYS_UTIME_H
66 # include <sys/utime.h>
67 #endif
69 #ifdef HAVE_PWD_H
70 # include <pwd.h>
71 #endif
73 #ifdef HAVE_SYS_SYSMACROS_H
74 # include <sys/sysmacros.h>
75 #endif
77 #include <sys/types.h>
78 #include <sys/stat.h>
80 #ifdef HAVE_SYS_MKDEV_H
81 # include <sys/mkdev.h>
82 #endif
84 #if defined(HAVE_FCNTL_H)
85 # include <fcntl.h>
86 #endif
88 #if defined(HAVE_SYS_TIME_H)
89 # include <sys/time.h>
90 #endif
92 #if !defined HAVE_LSTAT && !defined lstat
93 # define lstat stat
94 #endif
96 /* define system APIs */
97 #ifdef _WIN32
98 # include "win32/file.h"
99 # define STAT(p, s) rb_w32_ustati128((p), (s))
100 # undef lstat
101 # define lstat(p, s) rb_w32_ulstati128((p), (s))
102 # undef access
103 # define access(p, m) rb_w32_uaccess((p), (m))
104 # undef truncate
105 # define truncate(p, n) rb_w32_utruncate((p), (n))
106 # undef chmod
107 # define chmod(p, m) rb_w32_uchmod((p), (m))
108 # undef chown
109 # define chown(p, o, g) rb_w32_uchown((p), (o), (g))
110 # undef lchown
111 # define lchown(p, o, g) rb_w32_ulchown((p), (o), (g))
112 # undef utimensat
113 # define utimensat(s, p, t, f) rb_w32_uutimensat((s), (p), (t), (f))
114 # undef link
115 # define link(f, t) rb_w32_ulink((f), (t))
116 # undef unlink
117 # define unlink(p) rb_w32_uunlink(p)
118 # undef readlink
119 # define readlink(f, t, l) rb_w32_ureadlink((f), (t), (l))
120 # undef rename
121 # define rename(f, t) rb_w32_urename((f), (t))
122 # undef symlink
123 # define symlink(s, l) rb_w32_usymlink((s), (l))
125 # ifdef HAVE_REALPATH
126 /* Don't use native realpath(3) on Windows, as the check for
127 absolute paths does not work for drive letters. */
128 # undef HAVE_REALPATH
129 # endif
130 #else
131 # define STAT(p, s) stat((p), (s))
132 #endif /* _WIN32 */
134 #if defined _WIN32 || defined __APPLE__
135 # define USE_OSPATH 1
136 # define TO_OSPATH(str) rb_str_encode_ospath(str)
137 #else
138 # define USE_OSPATH 0
139 # define TO_OSPATH(str) (str)
140 #endif
142 /* utime may fail if time is out-of-range for the FS [ruby-dev:38277] */
143 #if defined DOSISH || defined __CYGWIN__
144 # define UTIME_EINVAL
145 #endif
147 /* Solaris 10 realpath(3) doesn't support File.realpath */
148 #if defined HAVE_REALPATH && defined __sun && defined __SVR4
149 #undef HAVE_REALPATH
150 #endif
152 #ifdef HAVE_REALPATH
153 # include <limits.h>
154 # include <stdlib.h>
155 #endif
157 #include "dln.h"
158 #include "encindex.h"
159 #include "id.h"
160 #include "internal.h"
161 #include "internal/compilers.h"
162 #include "internal/dir.h"
163 #include "internal/error.h"
164 #include "internal/file.h"
165 #include "internal/io.h"
166 #include "internal/load.h"
167 #include "internal/object.h"
168 #include "internal/process.h"
169 #include "internal/thread.h"
170 #include "internal/vm.h"
171 #include "ruby/encoding.h"
172 #include "ruby/thread.h"
173 #include "ruby/util.h"
175 VALUE rb_cFile;
176 VALUE rb_mFileTest;
177 VALUE rb_cStat;
179 static VALUE
180 file_path_convert(VALUE name)
182 #ifndef _WIN32 /* non Windows == Unix */
183 int fname_encidx = ENCODING_GET(name);
184 int fs_encidx;
185 if (ENCINDEX_US_ASCII != fname_encidx &&
186 ENCINDEX_ASCII_8BIT != fname_encidx &&
187 (fs_encidx = rb_filesystem_encindex()) != fname_encidx &&
188 rb_default_internal_encoding() &&
189 !rb_enc_str_asciionly_p(name)) {
190 /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */
191 /* fs_encoding should be ascii compatible */
192 rb_encoding *fname_encoding = rb_enc_from_index(fname_encidx);
193 rb_encoding *fs_encoding = rb_enc_from_index(fs_encidx);
194 name = rb_str_conv_enc(name, fname_encoding, fs_encoding);
196 #endif
197 return name;
200 static rb_encoding *
201 check_path_encoding(VALUE str)
203 rb_encoding *enc = rb_enc_get(str);
204 if (!rb_enc_asciicompat(enc)) {
205 rb_raise(rb_eEncCompatError, "path name must be ASCII-compatible (%s): %"PRIsVALUE,
206 rb_enc_name(enc), rb_str_inspect(str));
208 return enc;
211 VALUE
212 rb_get_path_check_to_string(VALUE obj)
214 VALUE tmp;
215 ID to_path;
217 if (RB_TYPE_P(obj, T_STRING)) {
218 return obj;
220 CONST_ID(to_path, "to_path");
221 tmp = rb_check_funcall_default(obj, to_path, 0, 0, obj);
222 StringValue(tmp);
223 return tmp;
226 VALUE
227 rb_get_path_check_convert(VALUE obj)
229 obj = file_path_convert(obj);
231 check_path_encoding(obj);
232 if (!rb_str_to_cstr(obj)) {
233 rb_raise(rb_eArgError, "path name contains null byte");
236 return rb_str_new4(obj);
239 VALUE
240 rb_get_path_no_checksafe(VALUE obj)
242 return rb_get_path(obj);
245 VALUE
246 rb_get_path(VALUE obj)
248 return rb_get_path_check_convert(rb_get_path_check_to_string(obj));
251 VALUE
252 rb_str_encode_ospath(VALUE path)
254 #if USE_OSPATH
255 int encidx = ENCODING_GET(path);
256 #if 0 && defined _WIN32
257 if (encidx == ENCINDEX_ASCII_8BIT) {
258 encidx = rb_filesystem_encindex();
260 #endif
261 if (encidx != ENCINDEX_ASCII_8BIT && encidx != ENCINDEX_UTF_8) {
262 rb_encoding *enc = rb_enc_from_index(encidx);
263 rb_encoding *utf8 = rb_utf8_encoding();
264 path = rb_str_conv_enc(path, enc, utf8);
266 #endif /* USE_OSPATH */
267 return path;
270 #ifdef __APPLE__
271 # define NORMALIZE_UTF8PATH 1
273 # ifdef HAVE_WORKING_FORK
274 static void
275 rb_CFString_class_initialize_before_fork(void)
278 * Since macOS 13, CFString family API used in
279 * rb_str_append_normalized_ospath may internally use Objective-C classes
280 * (NSTaggedPointerString and NSPlaceholderMutableString) for small strings.
282 * On the other hand, Objective-C classes should not be used for the first
283 * time in a fork()'ed but not exec()'ed process. Violations for this rule
284 * can result deadlock during class initialization, so Objective-C runtime
285 * conservatively crashes on such cases by default.
287 * Therefore, we need to use CFString API to initialize Objective-C classes
288 * used internally *before* fork().
290 * For future changes, please note that this initialization process cannot
291 * be done in ctor because NSTaggedPointerString in CoreFoundation is enabled
292 * after CFStringInitializeTaggedStrings(), which is called during loading
293 * Objective-C runtime after ctor.
294 * For more details, see https://bugs.ruby-lang.org/issues/18912
297 /* Enough small but non-empty ASCII string to fit in NSTaggedPointerString. */
298 const char small_str[] = "/";
299 long len = sizeof(small_str) - 1;
301 const CFAllocatorRef alloc = kCFAllocatorDefault;
302 CFStringRef s = CFStringCreateWithBytesNoCopy(alloc,
303 (const UInt8 *)small_str,
304 len, kCFStringEncodingUTF8,
305 FALSE, kCFAllocatorNull);
306 CFMutableStringRef m = CFStringCreateMutableCopy(alloc, len, s);
307 CFRelease(m);
308 CFRelease(s);
310 # endif /* HAVE_WORKING_FORK */
312 static VALUE
313 rb_str_append_normalized_ospath(VALUE str, const char *ptr, long len)
315 CFIndex buflen = 0;
316 CFRange all;
317 CFStringRef s = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault,
318 (const UInt8 *)ptr, len,
319 kCFStringEncodingUTF8, FALSE,
320 kCFAllocatorNull);
321 CFMutableStringRef m = CFStringCreateMutableCopy(kCFAllocatorDefault, len, s);
322 long oldlen = RSTRING_LEN(str);
324 CFStringNormalize(m, kCFStringNormalizationFormC);
325 all = CFRangeMake(0, CFStringGetLength(m));
326 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE, NULL, 0, &buflen);
327 rb_str_modify_expand(str, buflen);
328 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE,
329 (UInt8 *)(RSTRING_PTR(str) + oldlen), buflen, &buflen);
330 rb_str_set_len(str, oldlen + buflen);
331 CFRelease(m);
332 CFRelease(s);
333 return str;
336 VALUE
337 rb_str_normalize_ospath(const char *ptr, long len)
339 const char *p = ptr;
340 const char *e = ptr + len;
341 const char *p1 = p;
342 VALUE str = rb_str_buf_new(len);
343 rb_encoding *enc = rb_utf8_encoding();
344 rb_enc_associate(str, enc);
346 while (p < e) {
347 int l, c;
348 int r = rb_enc_precise_mbclen(p, e, enc);
349 if (!MBCLEN_CHARFOUND_P(r)) {
350 /* invalid byte shall not happen but */
351 static const char invalid[3] = "\xEF\xBF\xBD";
352 rb_str_append_normalized_ospath(str, p1, p-p1);
353 rb_str_cat(str, invalid, sizeof(invalid));
354 p += 1;
355 p1 = p;
356 continue;
358 l = MBCLEN_CHARFOUND_LEN(r);
359 c = rb_enc_mbc_to_codepoint(p, e, enc);
360 if ((0x2000 <= c && c <= 0x2FFF) || (0xF900 <= c && c <= 0xFAFF) ||
361 (0x2F800 <= c && c <= 0x2FAFF)) {
362 if (p - p1 > 0) {
363 rb_str_append_normalized_ospath(str, p1, p-p1);
365 rb_str_cat(str, p, l);
366 p += l;
367 p1 = p;
369 else {
370 p += l;
373 if (p - p1 > 0) {
374 rb_str_append_normalized_ospath(str, p1, p-p1);
377 return str;
380 static int
381 ignored_char_p(const char *p, const char *e, rb_encoding *enc)
383 unsigned char c;
384 if (p+3 > e) return 0;
385 switch ((unsigned char)*p) {
386 case 0xe2:
387 switch ((unsigned char)p[1]) {
388 case 0x80:
389 c = (unsigned char)p[2];
390 /* c >= 0x200c && c <= 0x200f */
391 if (c >= 0x8c && c <= 0x8f) return 3;
392 /* c >= 0x202a && c <= 0x202e */
393 if (c >= 0xaa && c <= 0xae) return 3;
394 return 0;
395 case 0x81:
396 c = (unsigned char)p[2];
397 /* c >= 0x206a && c <= 0x206f */
398 if (c >= 0xaa && c <= 0xaf) return 3;
399 return 0;
401 break;
402 case 0xef:
403 /* c == 0xfeff */
404 if ((unsigned char)p[1] == 0xbb &&
405 (unsigned char)p[2] == 0xbf)
406 return 3;
407 break;
409 return 0;
411 #else /* !__APPLE__ */
412 # define NORMALIZE_UTF8PATH 0
413 #endif /* __APPLE__ */
415 #define apply2args(n) (rb_check_arity(argc, n, UNLIMITED_ARGUMENTS), argc-=n)
417 struct apply_filename {
418 const char *ptr;
419 VALUE path;
422 struct apply_arg {
423 int i;
424 int argc;
425 int errnum;
426 int (*func)(const char *, void *);
427 void *arg;
428 struct apply_filename fn[FLEX_ARY_LEN];
431 static void *
432 no_gvl_apply2files(void *ptr)
434 struct apply_arg *aa = ptr;
436 for (aa->i = 0; aa->i < aa->argc; aa->i++) {
437 if (aa->func(aa->fn[aa->i].ptr, aa->arg) < 0) {
438 aa->errnum = errno;
439 break;
442 return 0;
445 #ifdef UTIME_EINVAL
446 NORETURN(static void utime_failed(struct apply_arg *));
447 static int utime_internal(const char *, void *);
448 #endif
450 static VALUE
451 apply2files(int (*func)(const char *, void *), int argc, VALUE *argv, void *arg)
453 VALUE v;
454 const size_t size = sizeof(struct apply_filename);
455 const long len = (long)(offsetof(struct apply_arg, fn) + (size * argc));
456 struct apply_arg *aa = ALLOCV(v, len);
458 aa->errnum = 0;
459 aa->argc = argc;
460 aa->arg = arg;
461 aa->func = func;
463 for (aa->i = 0; aa->i < argc; aa->i++) {
464 VALUE path = rb_get_path(argv[aa->i]);
466 path = rb_str_encode_ospath(path);
467 aa->fn[aa->i].ptr = RSTRING_PTR(path);
468 aa->fn[aa->i].path = path;
471 IO_WITHOUT_GVL(no_gvl_apply2files, aa);
472 if (aa->errnum) {
473 #ifdef UTIME_EINVAL
474 if (func == utime_internal) {
475 utime_failed(aa);
477 #endif
478 rb_syserr_fail_path(aa->errnum, aa->fn[aa->i].path);
480 if (v) {
481 ALLOCV_END(v);
483 return LONG2FIX(argc);
486 static const rb_data_type_t stat_data_type = {
487 "stat",
489 NULL,
490 RUBY_TYPED_DEFAULT_FREE,
491 NULL, // No external memory to report
493 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
496 struct rb_stat {
497 struct stat stat;
498 bool initialized;
501 static VALUE
502 stat_new_0(VALUE klass, const struct stat *st)
504 struct rb_stat *rb_st;
505 VALUE obj = TypedData_Make_Struct(klass, struct rb_stat, &stat_data_type, rb_st);
506 if (st) {
507 rb_st->stat = *st;
508 rb_st->initialized = true;
510 return obj;
513 VALUE
514 rb_stat_new(const struct stat *st)
516 return stat_new_0(rb_cStat, st);
519 static struct stat*
520 get_stat(VALUE self)
522 struct rb_stat* rb_st;
523 TypedData_Get_Struct(self, struct rb_stat, &stat_data_type, rb_st);
524 if (!rb_st->initialized) rb_raise(rb_eTypeError, "uninitialized File::Stat");
525 return &rb_st->stat;
528 static struct timespec stat_mtimespec(const struct stat *st);
531 * call-seq:
532 * stat <=> other_stat -> -1, 0, 1, nil
534 * Compares File::Stat objects by comparing their respective modification
535 * times.
537 * +nil+ is returned if +other_stat+ is not a File::Stat object
539 * f1 = File.new("f1", "w")
540 * sleep 1
541 * f2 = File.new("f2", "w")
542 * f1.stat <=> f2.stat #=> -1
545 static VALUE
546 rb_stat_cmp(VALUE self, VALUE other)
548 if (rb_obj_is_kind_of(other, rb_obj_class(self))) {
549 struct timespec ts1 = stat_mtimespec(get_stat(self));
550 struct timespec ts2 = stat_mtimespec(get_stat(other));
551 if (ts1.tv_sec == ts2.tv_sec) {
552 if (ts1.tv_nsec == ts2.tv_nsec) return INT2FIX(0);
553 if (ts1.tv_nsec < ts2.tv_nsec) return INT2FIX(-1);
554 return INT2FIX(1);
556 if (ts1.tv_sec < ts2.tv_sec) return INT2FIX(-1);
557 return INT2FIX(1);
559 return Qnil;
562 #define ST2UINT(val) ((val) & ~(~1UL << (sizeof(val) * CHAR_BIT - 1)))
564 #ifndef NUM2DEVT
565 # define NUM2DEVT(v) NUM2UINT(v)
566 #endif
567 #ifndef DEVT2NUM
568 # define DEVT2NUM(v) UINT2NUM(v)
569 #endif
570 #ifndef PRI_DEVT_PREFIX
571 # define PRI_DEVT_PREFIX ""
572 #endif
575 * call-seq:
576 * stat.dev -> integer
578 * Returns an integer representing the device on which <i>stat</i>
579 * resides.
581 * File.stat("testfile").dev #=> 774
584 static VALUE
585 rb_stat_dev(VALUE self)
587 #if SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_DEV_T
588 return DEVT2NUM(get_stat(self)->st_dev);
589 #elif SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_LONG
590 return ULONG2NUM(get_stat(self)->st_dev);
591 #else
592 return ULL2NUM(get_stat(self)->st_dev);
593 #endif
597 * call-seq:
598 * stat.dev_major -> integer
600 * Returns the major part of <code>File_Stat#dev</code> or
601 * <code>nil</code>.
603 * File.stat("/dev/fd1").dev_major #=> 2
604 * File.stat("/dev/tty").dev_major #=> 5
607 static VALUE
608 rb_stat_dev_major(VALUE self)
610 #if defined(major)
611 return UINT2NUM(major(get_stat(self)->st_dev));
612 #else
613 return Qnil;
614 #endif
618 * call-seq:
619 * stat.dev_minor -> integer
621 * Returns the minor part of <code>File_Stat#dev</code> or
622 * <code>nil</code>.
624 * File.stat("/dev/fd1").dev_minor #=> 1
625 * File.stat("/dev/tty").dev_minor #=> 0
628 static VALUE
629 rb_stat_dev_minor(VALUE self)
631 #if defined(minor)
632 return UINT2NUM(minor(get_stat(self)->st_dev));
633 #else
634 return Qnil;
635 #endif
639 * call-seq:
640 * stat.ino -> integer
642 * Returns the inode number for <i>stat</i>.
644 * File.stat("testfile").ino #=> 1083669
648 static VALUE
649 rb_stat_ino(VALUE self)
651 #ifdef HAVE_STRUCT_STAT_ST_INOHIGH
652 /* assume INTEGER_PACK_LSWORD_FIRST and st_inohigh is just next of st_ino */
653 return rb_integer_unpack(&get_stat(self)->st_ino, 2,
654 SIZEOF_STRUCT_STAT_ST_INO, 0,
655 INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER|
656 INTEGER_PACK_2COMP);
657 #elif SIZEOF_STRUCT_STAT_ST_INO > SIZEOF_LONG
658 return ULL2NUM(get_stat(self)->st_ino);
659 #else
660 return ULONG2NUM(get_stat(self)->st_ino);
661 #endif
665 * call-seq:
666 * stat.mode -> integer
668 * Returns an integer representing the permission bits of
669 * <i>stat</i>. The meaning of the bits is platform dependent; on
670 * Unix systems, see <code>stat(2)</code>.
672 * File.chmod(0644, "testfile") #=> 1
673 * s = File.stat("testfile")
674 * sprintf("%o", s.mode) #=> "100644"
677 static VALUE
678 rb_stat_mode(VALUE self)
680 return UINT2NUM(ST2UINT(get_stat(self)->st_mode));
684 * call-seq:
685 * stat.nlink -> integer
687 * Returns the number of hard links to <i>stat</i>.
689 * File.stat("testfile").nlink #=> 1
690 * File.link("testfile", "testfile.bak") #=> 0
691 * File.stat("testfile").nlink #=> 2
695 static VALUE
696 rb_stat_nlink(VALUE self)
698 /* struct stat::st_nlink is nlink_t in POSIX. Not the case for Windows. */
699 const struct stat *ptr = get_stat(self);
701 if (sizeof(ptr->st_nlink) <= sizeof(int)) {
702 return UINT2NUM((unsigned)ptr->st_nlink);
704 else if (sizeof(ptr->st_nlink) == sizeof(long)) {
705 return ULONG2NUM((unsigned long)ptr->st_nlink);
707 else if (sizeof(ptr->st_nlink) == sizeof(LONG_LONG)) {
708 return ULL2NUM((unsigned LONG_LONG)ptr->st_nlink);
710 else {
711 rb_bug(":FIXME: don't know what to do");
716 * call-seq:
717 * stat.uid -> integer
719 * Returns the numeric user id of the owner of <i>stat</i>.
721 * File.stat("testfile").uid #=> 501
725 static VALUE
726 rb_stat_uid(VALUE self)
728 return UIDT2NUM(get_stat(self)->st_uid);
732 * call-seq:
733 * stat.gid -> integer
735 * Returns the numeric group id of the owner of <i>stat</i>.
737 * File.stat("testfile").gid #=> 500
741 static VALUE
742 rb_stat_gid(VALUE self)
744 return GIDT2NUM(get_stat(self)->st_gid);
748 * call-seq:
749 * stat.rdev -> integer or nil
751 * Returns an integer representing the device type on which
752 * <i>stat</i> resides. Returns <code>nil</code> if the operating
753 * system doesn't support this feature.
755 * File.stat("/dev/fd1").rdev #=> 513
756 * File.stat("/dev/tty").rdev #=> 1280
759 static VALUE
760 rb_stat_rdev(VALUE self)
762 #ifdef HAVE_STRUCT_STAT_ST_RDEV
763 # if SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_DEV_T
764 return DEVT2NUM(get_stat(self)->st_rdev);
765 # elif SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_LONG
766 return ULONG2NUM(get_stat(self)->st_rdev);
767 # else
768 return ULL2NUM(get_stat(self)->st_rdev);
769 # endif
770 #else
771 return Qnil;
772 #endif
776 * call-seq:
777 * stat.rdev_major -> integer
779 * Returns the major part of <code>File_Stat#rdev</code> or
780 * <code>nil</code>.
782 * File.stat("/dev/fd1").rdev_major #=> 2
783 * File.stat("/dev/tty").rdev_major #=> 5
786 static VALUE
787 rb_stat_rdev_major(VALUE self)
789 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(major)
790 return UINT2NUM(major(get_stat(self)->st_rdev));
791 #else
792 return Qnil;
793 #endif
797 * call-seq:
798 * stat.rdev_minor -> integer
800 * Returns the minor part of <code>File_Stat#rdev</code> or
801 * <code>nil</code>.
803 * File.stat("/dev/fd1").rdev_minor #=> 1
804 * File.stat("/dev/tty").rdev_minor #=> 0
807 static VALUE
808 rb_stat_rdev_minor(VALUE self)
810 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(minor)
811 return UINT2NUM(minor(get_stat(self)->st_rdev));
812 #else
813 return Qnil;
814 #endif
818 * call-seq:
819 * stat.size -> integer
821 * Returns the size of <i>stat</i> in bytes.
823 * File.stat("testfile").size #=> 66
826 static VALUE
827 rb_stat_size(VALUE self)
829 return OFFT2NUM(get_stat(self)->st_size);
833 * call-seq:
834 * stat.blksize -> integer or nil
836 * Returns the native file system's block size. Will return <code>nil</code>
837 * on platforms that don't support this information.
839 * File.stat("testfile").blksize #=> 4096
843 static VALUE
844 rb_stat_blksize(VALUE self)
846 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
847 return ULONG2NUM(get_stat(self)->st_blksize);
848 #else
849 return Qnil;
850 #endif
854 * call-seq:
855 * stat.blocks -> integer or nil
857 * Returns the number of native file system blocks allocated for this
858 * file, or <code>nil</code> if the operating system doesn't
859 * support this feature.
861 * File.stat("testfile").blocks #=> 2
864 static VALUE
865 rb_stat_blocks(VALUE self)
867 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
868 # if SIZEOF_STRUCT_STAT_ST_BLOCKS > SIZEOF_LONG
869 return ULL2NUM(get_stat(self)->st_blocks);
870 # else
871 return ULONG2NUM(get_stat(self)->st_blocks);
872 # endif
873 #else
874 return Qnil;
875 #endif
878 static struct timespec
879 stat_atimespec(const struct stat *st)
881 struct timespec ts;
882 ts.tv_sec = st->st_atime;
883 #if defined(HAVE_STRUCT_STAT_ST_ATIM)
884 ts.tv_nsec = st->st_atim.tv_nsec;
885 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
886 ts.tv_nsec = st->st_atimespec.tv_nsec;
887 #elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
888 ts.tv_nsec = (long)st->st_atimensec;
889 #else
890 ts.tv_nsec = 0;
891 #endif
892 return ts;
895 static VALUE
896 stat_time(const struct timespec ts)
898 return rb_time_nano_new(ts.tv_sec, ts.tv_nsec);
901 static VALUE
902 stat_atime(const struct stat *st)
904 return stat_time(stat_atimespec(st));
907 static struct timespec
908 stat_mtimespec(const struct stat *st)
910 struct timespec ts;
911 ts.tv_sec = st->st_mtime;
912 #if defined(HAVE_STRUCT_STAT_ST_MTIM)
913 ts.tv_nsec = st->st_mtim.tv_nsec;
914 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
915 ts.tv_nsec = st->st_mtimespec.tv_nsec;
916 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
917 ts.tv_nsec = (long)st->st_mtimensec;
918 #else
919 ts.tv_nsec = 0;
920 #endif
921 return ts;
924 static VALUE
925 stat_mtime(const struct stat *st)
927 return stat_time(stat_mtimespec(st));
930 static struct timespec
931 stat_ctimespec(const struct stat *st)
933 struct timespec ts;
934 ts.tv_sec = st->st_ctime;
935 #if defined(HAVE_STRUCT_STAT_ST_CTIM)
936 ts.tv_nsec = st->st_ctim.tv_nsec;
937 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
938 ts.tv_nsec = st->st_ctimespec.tv_nsec;
939 #elif defined(HAVE_STRUCT_STAT_ST_CTIMENSEC)
940 ts.tv_nsec = (long)st->st_ctimensec;
941 #else
942 ts.tv_nsec = 0;
943 #endif
944 return ts;
947 static VALUE
948 stat_ctime(const struct stat *st)
950 return stat_time(stat_ctimespec(st));
953 #define HAVE_STAT_BIRTHTIME
954 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
955 typedef struct stat statx_data;
956 static VALUE
957 stat_birthtime(const struct stat *st)
959 const struct timespec *ts = &st->st_birthtimespec;
960 return rb_time_nano_new(ts->tv_sec, ts->tv_nsec);
962 #elif defined(_WIN32)
963 typedef struct stat statx_data;
964 # define stat_birthtime stat_ctime
965 #else
966 # undef HAVE_STAT_BIRTHTIME
967 #endif /* defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) */
970 * call-seq:
971 * stat.atime -> time
973 * Returns the last access time for this file as an object of class
974 * Time.
976 * File.stat("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
980 static VALUE
981 rb_stat_atime(VALUE self)
983 return stat_atime(get_stat(self));
987 * call-seq:
988 * stat.mtime -> time
990 * Returns the modification time of <i>stat</i>.
992 * File.stat("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
996 static VALUE
997 rb_stat_mtime(VALUE self)
999 return stat_mtime(get_stat(self));
1003 * call-seq:
1004 * stat.ctime -> time
1006 * Returns the change time for <i>stat</i> (that is, the time
1007 * directory information about the file was changed, not the file
1008 * itself).
1010 * Note that on Windows (NTFS), returns creation time (birth time).
1012 * File.stat("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
1016 static VALUE
1017 rb_stat_ctime(VALUE self)
1019 return stat_ctime(get_stat(self));
1022 #if defined(HAVE_STAT_BIRTHTIME)
1024 * call-seq:
1025 * stat.birthtime -> time
1027 * Returns the birth time for <i>stat</i>.
1029 * If the platform doesn't have birthtime, raises NotImplementedError.
1031 * File.write("testfile", "foo")
1032 * sleep 10
1033 * File.write("testfile", "bar")
1034 * sleep 10
1035 * File.chmod(0644, "testfile")
1036 * sleep 10
1037 * File.read("testfile")
1038 * File.stat("testfile").birthtime #=> 2014-02-24 11:19:17 +0900
1039 * File.stat("testfile").mtime #=> 2014-02-24 11:19:27 +0900
1040 * File.stat("testfile").ctime #=> 2014-02-24 11:19:37 +0900
1041 * File.stat("testfile").atime #=> 2014-02-24 11:19:47 +0900
1045 static VALUE
1046 rb_stat_birthtime(VALUE self)
1048 return stat_birthtime(get_stat(self));
1050 #else
1051 # define rb_stat_birthtime rb_f_notimplement
1052 #endif
1055 * call-seq:
1056 * stat.inspect -> string
1058 * Produce a nicely formatted description of <i>stat</i>.
1060 * File.stat("/etc/passwd").inspect
1061 * #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
1062 * # nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
1063 * # blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
1064 * # mtime=Fri Sep 12 15:41:41 CDT 2003,
1065 * # ctime=Mon Oct 27 11:20:27 CST 2003,
1066 * # birthtime=Mon Aug 04 08:13:49 CDT 2003>"
1069 static VALUE
1070 rb_stat_inspect(VALUE self)
1072 VALUE str;
1073 size_t i;
1074 static const struct {
1075 const char *name;
1076 VALUE (*func)(VALUE);
1077 } member[] = {
1078 {"dev", rb_stat_dev},
1079 {"ino", rb_stat_ino},
1080 {"mode", rb_stat_mode},
1081 {"nlink", rb_stat_nlink},
1082 {"uid", rb_stat_uid},
1083 {"gid", rb_stat_gid},
1084 {"rdev", rb_stat_rdev},
1085 {"size", rb_stat_size},
1086 {"blksize", rb_stat_blksize},
1087 {"blocks", rb_stat_blocks},
1088 {"atime", rb_stat_atime},
1089 {"mtime", rb_stat_mtime},
1090 {"ctime", rb_stat_ctime},
1091 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1092 {"birthtime", rb_stat_birthtime},
1093 #endif
1096 struct rb_stat* rb_st;
1097 TypedData_Get_Struct(self, struct rb_stat, &stat_data_type, rb_st);
1098 if (!rb_st->initialized) {
1099 return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
1102 str = rb_str_buf_new2("#<");
1103 rb_str_buf_cat2(str, rb_obj_classname(self));
1104 rb_str_buf_cat2(str, " ");
1106 for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) {
1107 VALUE v;
1109 if (i > 0) {
1110 rb_str_buf_cat2(str, ", ");
1112 rb_str_buf_cat2(str, member[i].name);
1113 rb_str_buf_cat2(str, "=");
1114 v = (*member[i].func)(self);
1115 if (i == 2) { /* mode */
1116 rb_str_catf(str, "0%lo", (unsigned long)NUM2ULONG(v));
1118 else if (i == 0 || i == 6) { /* dev/rdev */
1119 rb_str_catf(str, "0x%"PRI_DEVT_PREFIX"x", NUM2DEVT(v));
1121 else {
1122 rb_str_append(str, rb_inspect(v));
1125 rb_str_buf_cat2(str, ">");
1127 return str;
1130 typedef struct no_gvl_stat_data {
1131 struct stat *st;
1132 union {
1133 const char *path;
1134 int fd;
1135 } file;
1136 } no_gvl_stat_data;
1138 static VALUE
1139 no_gvl_fstat(void *data)
1141 no_gvl_stat_data *arg = data;
1142 return (VALUE)fstat(arg->file.fd, arg->st);
1145 static int
1146 fstat_without_gvl(int fd, struct stat *st)
1148 no_gvl_stat_data data;
1150 data.file.fd = fd;
1151 data.st = st;
1153 return (int)(VALUE)rb_thread_io_blocking_region(no_gvl_fstat, &data, fd);
1156 static void *
1157 no_gvl_stat(void * data)
1159 no_gvl_stat_data *arg = data;
1160 return (void *)(VALUE)STAT(arg->file.path, arg->st);
1163 static int
1164 stat_without_gvl(const char *path, struct stat *st)
1166 no_gvl_stat_data data;
1168 data.file.path = path;
1169 data.st = st;
1171 return IO_WITHOUT_GVL_INT(no_gvl_stat, &data);
1174 #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1175 defined(HAVE_STRUCT_STATX_STX_BTIME)
1177 # ifndef HAVE_STATX
1178 # ifdef HAVE_SYSCALL_H
1179 # include <syscall.h>
1180 # elif defined HAVE_SYS_SYSCALL_H
1181 # include <sys/syscall.h>
1182 # endif
1183 # if defined __linux__
1184 # include <linux/stat.h>
1185 static inline int
1186 statx(int dirfd, const char *pathname, int flags,
1187 unsigned int mask, struct statx *statxbuf)
1189 return (int)syscall(__NR_statx, dirfd, pathname, flags, mask, statxbuf);
1191 # endif /* __linux__ */
1192 # endif /* HAVE_STATX */
1194 typedef struct no_gvl_statx_data {
1195 struct statx *stx;
1196 int fd;
1197 const char *path;
1198 int flags;
1199 unsigned int mask;
1200 } no_gvl_statx_data;
1202 static VALUE
1203 io_blocking_statx(void *data)
1205 no_gvl_statx_data *arg = data;
1206 return (VALUE)statx(arg->fd, arg->path, arg->flags, arg->mask, arg->stx);
1209 static void *
1210 no_gvl_statx(void *data)
1212 return (void *)io_blocking_statx(data);
1215 static int
1216 statx_without_gvl(const char *path, struct statx *stx, unsigned int mask)
1218 no_gvl_statx_data data = {stx, AT_FDCWD, path, 0, mask};
1220 /* call statx(2) with pathname */
1221 return IO_WITHOUT_GVL_INT(no_gvl_statx, &data);
1224 static int
1225 fstatx_without_gvl(int fd, struct statx *stx, unsigned int mask)
1227 no_gvl_statx_data data = {stx, fd, "", AT_EMPTY_PATH, mask};
1229 /* call statx(2) with fd */
1230 return (int)rb_thread_io_blocking_region(io_blocking_statx, &data, fd);
1233 static int
1234 rb_statx(VALUE file, struct statx *stx, unsigned int mask)
1236 VALUE tmp;
1237 int result;
1239 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1240 if (!NIL_P(tmp)) {
1241 rb_io_t *fptr;
1242 GetOpenFile(tmp, fptr);
1243 result = fstatx_without_gvl(fptr->fd, stx, mask);
1244 file = tmp;
1246 else {
1247 FilePathValue(file);
1248 file = rb_str_encode_ospath(file);
1249 result = statx_without_gvl(RSTRING_PTR(file), stx, mask);
1251 RB_GC_GUARD(file);
1252 return result;
1255 # define statx_has_birthtime(st) ((st)->stx_mask & STATX_BTIME)
1257 NORETURN(static void statx_notimplement(const char *field_name));
1259 /* rb_notimplement() shows "function is unimplemented on this machine".
1260 It is not applicable to statx which behavior depends on the filesystem. */
1261 static void
1262 statx_notimplement(const char *field_name)
1264 rb_raise(rb_eNotImpError,
1265 "%s is unimplemented on this filesystem",
1266 field_name);
1269 static VALUE
1270 statx_birthtime(const struct statx *stx, VALUE fname)
1272 if (!statx_has_birthtime(stx)) {
1273 /* birthtime is not supported on the filesystem */
1274 statx_notimplement("birthtime");
1276 return rb_time_nano_new((time_t)stx->stx_btime.tv_sec, stx->stx_btime.tv_nsec);
1279 typedef struct statx statx_data;
1280 # define HAVE_STAT_BIRTHTIME
1282 #elif defined(HAVE_STAT_BIRTHTIME)
1283 # define statx_without_gvl(path, st, mask) stat_without_gvl(path, st)
1284 # define fstatx_without_gvl(fd, st, mask) fstat_without_gvl(fd, st)
1285 # define statx_birthtime(st, fname) stat_birthtime(st)
1286 # define statx_has_birthtime(st) 1
1287 # define rb_statx(file, st, mask) rb_stat(file, st)
1288 #else
1289 # define statx_has_birthtime(st) 0
1290 #endif /* !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1291 defined(HAVE_STRUCT_STATX_STX_BTIME) */
1293 static int
1294 rb_stat(VALUE file, struct stat *st)
1296 VALUE tmp;
1297 int result;
1299 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1300 if (!NIL_P(tmp)) {
1301 rb_io_t *fptr;
1303 GetOpenFile(tmp, fptr);
1304 result = fstat_without_gvl(fptr->fd, st);
1305 file = tmp;
1307 else {
1308 FilePathValue(file);
1309 file = rb_str_encode_ospath(file);
1310 result = stat_without_gvl(RSTRING_PTR(file), st);
1312 RB_GC_GUARD(file);
1313 return result;
1317 * call-seq:
1318 * File.stat(filepath) -> stat
1320 * Returns a File::Stat object for the file at +filepath+ (see File::Stat):
1322 * File.stat('t.txt').class # => File::Stat
1326 static VALUE
1327 rb_file_s_stat(VALUE klass, VALUE fname)
1329 struct stat st;
1331 FilePathValue(fname);
1332 fname = rb_str_encode_ospath(fname);
1333 if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) {
1334 rb_sys_fail_path(fname);
1336 return rb_stat_new(&st);
1340 * call-seq:
1341 * ios.stat -> stat
1343 * Returns status information for <em>ios</em> as an object of type
1344 * File::Stat.
1346 * f = File.new("testfile")
1347 * s = f.stat
1348 * "%o" % s.mode #=> "100644"
1349 * s.blksize #=> 4096
1350 * s.atime #=> Wed Apr 09 08:53:54 CDT 2003
1354 static VALUE
1355 rb_io_stat(VALUE obj)
1357 rb_io_t *fptr;
1358 struct stat st;
1360 GetOpenFile(obj, fptr);
1361 if (fstat(fptr->fd, &st) == -1) {
1362 rb_sys_fail_path(fptr->pathv);
1364 return rb_stat_new(&st);
1367 #ifdef HAVE_LSTAT
1368 static void *
1369 no_gvl_lstat(void *ptr)
1371 no_gvl_stat_data *arg = ptr;
1372 return (void *)(VALUE)lstat(arg->file.path, arg->st);
1375 static int
1376 lstat_without_gvl(const char *path, struct stat *st)
1378 no_gvl_stat_data data;
1380 data.file.path = path;
1381 data.st = st;
1383 return IO_WITHOUT_GVL_INT(no_gvl_lstat, &data);
1385 #endif /* HAVE_LSTAT */
1388 * call-seq:
1389 * File.lstat(filepath) -> stat
1391 * Like File::stat, but does not follow the last symbolic link;
1392 * instead, returns a File::Stat object for the link itself.
1394 * File.symlink('t.txt', 'symlink')
1395 * File.stat('symlink').size # => 47
1396 * File.lstat('symlink').size # => 5
1400 static VALUE
1401 rb_file_s_lstat(VALUE klass, VALUE fname)
1403 #ifdef HAVE_LSTAT
1404 struct stat st;
1406 FilePathValue(fname);
1407 fname = rb_str_encode_ospath(fname);
1408 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
1409 rb_sys_fail_path(fname);
1411 return rb_stat_new(&st);
1412 #else
1413 return rb_file_s_stat(klass, fname);
1414 #endif
1418 * call-seq:
1419 * lstat -> stat
1421 * Like File#stat, but does not follow the last symbolic link;
1422 * instead, returns a File::Stat object for the link itself:
1424 * File.symlink('t.txt', 'symlink')
1425 * f = File.new('symlink')
1426 * f.stat.size # => 47
1427 * f.lstat.size # => 11
1431 static VALUE
1432 rb_file_lstat(VALUE obj)
1434 #ifdef HAVE_LSTAT
1435 rb_io_t *fptr;
1436 struct stat st;
1437 VALUE path;
1439 GetOpenFile(obj, fptr);
1440 if (NIL_P(fptr->pathv)) return Qnil;
1441 path = rb_str_encode_ospath(fptr->pathv);
1442 if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) {
1443 rb_sys_fail_path(fptr->pathv);
1445 return rb_stat_new(&st);
1446 #else
1447 return rb_io_stat(obj);
1448 #endif
1451 static int
1452 rb_group_member(GETGROUPS_T gid)
1454 #if defined(_WIN32) || !defined(HAVE_GETGROUPS)
1455 return FALSE;
1456 #else
1457 int rv = FALSE;
1458 int groups;
1459 VALUE v = 0;
1460 GETGROUPS_T *gary;
1461 int anum = -1;
1463 if (getgid() == gid || getegid() == gid)
1464 return TRUE;
1466 groups = getgroups(0, NULL);
1467 gary = ALLOCV_N(GETGROUPS_T, v, groups);
1468 anum = getgroups(groups, gary);
1469 while (--anum >= 0) {
1470 if (gary[anum] == gid) {
1471 rv = TRUE;
1472 break;
1475 if (v)
1476 ALLOCV_END(v);
1478 return rv;
1479 #endif /* defined(_WIN32) || !defined(HAVE_GETGROUPS) */
1482 #ifndef S_IXUGO
1483 # define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
1484 #endif
1486 #if defined(S_IXGRP) && !defined(_WIN32) && !defined(__CYGWIN__)
1487 #define USE_GETEUID 1
1488 #endif
1490 #ifndef HAVE_EACCESS
1492 eaccess(const char *path, int mode)
1494 #ifdef USE_GETEUID
1495 struct stat st;
1496 rb_uid_t euid;
1498 euid = geteuid();
1500 /* no setuid nor setgid. run shortcut. */
1501 if (getuid() == euid && getgid() == getegid())
1502 return access(path, mode);
1504 if (STAT(path, &st) < 0)
1505 return -1;
1507 if (euid == 0) {
1508 /* Root can read or write any file. */
1509 if (!(mode & X_OK))
1510 return 0;
1512 /* Root can execute any file that has any one of the execute
1513 bits set. */
1514 if (st.st_mode & S_IXUGO)
1515 return 0;
1517 return -1;
1520 if (st.st_uid == euid) /* owner */
1521 mode <<= 6;
1522 else if (rb_group_member(st.st_gid))
1523 mode <<= 3;
1525 if ((int)(st.st_mode & mode) == mode) return 0;
1527 return -1;
1528 #else
1529 return access(path, mode);
1530 #endif /* USE_GETEUID */
1532 #endif /* HAVE_EACCESS */
1534 struct access_arg {
1535 const char *path;
1536 int mode;
1539 static void *
1540 nogvl_eaccess(void *ptr)
1542 struct access_arg *aa = ptr;
1544 return (void *)(VALUE)eaccess(aa->path, aa->mode);
1547 static int
1548 rb_eaccess(VALUE fname, int mode)
1550 struct access_arg aa;
1552 FilePathValue(fname);
1553 fname = rb_str_encode_ospath(fname);
1554 aa.path = StringValueCStr(fname);
1555 aa.mode = mode;
1557 return IO_WITHOUT_GVL_INT(nogvl_eaccess, &aa);
1560 static void *
1561 nogvl_access(void *ptr)
1563 struct access_arg *aa = ptr;
1565 return (void *)(VALUE)access(aa->path, aa->mode);
1568 static int
1569 rb_access(VALUE fname, int mode)
1571 struct access_arg aa;
1573 FilePathValue(fname);
1574 fname = rb_str_encode_ospath(fname);
1575 aa.path = StringValueCStr(fname);
1576 aa.mode = mode;
1578 return IO_WITHOUT_GVL_INT(nogvl_access, &aa);
1582 * Document-class: FileTest
1584 * FileTest implements file test operations similar to those used in
1585 * File::Stat. It exists as a standalone module, and its methods are
1586 * also insinuated into the File class. (Note that this is not done
1587 * by inclusion: the interpreter cheats).
1592 * call-seq:
1593 * File.directory?(path) -> true or false
1595 * With string +object+ given, returns +true+ if +path+ is a string path
1596 * leading to a directory, or to a symbolic link to a directory; +false+ otherwise:
1598 * File.directory?('.') # => true
1599 * File.directory?('foo') # => false
1600 * File.symlink('.', 'dirlink') # => 0
1601 * File.directory?('dirlink') # => true
1602 * File.symlink('t,txt', 'filelink') # => 0
1603 * File.directory?('filelink') # => false
1605 * Argument +path+ can be an IO object.
1609 VALUE
1610 rb_file_directory_p(VALUE obj, VALUE fname)
1612 #ifndef S_ISDIR
1613 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1614 #endif
1616 struct stat st;
1618 if (rb_stat(fname, &st) < 0) return Qfalse;
1619 if (S_ISDIR(st.st_mode)) return Qtrue;
1620 return Qfalse;
1624 * call-seq:
1625 * File.pipe?(filepath) -> true or false
1627 * Returns +true+ if +filepath+ points to a pipe, +false+ otherwise:
1629 * File.mkfifo('tmp/fifo')
1630 * File.pipe?('tmp/fifo') # => true
1631 * File.pipe?('t.txt') # => false
1635 static VALUE
1636 rb_file_pipe_p(VALUE obj, VALUE fname)
1638 #ifdef S_IFIFO
1639 # ifndef S_ISFIFO
1640 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
1641 # endif
1643 struct stat st;
1645 if (rb_stat(fname, &st) < 0) return Qfalse;
1646 if (S_ISFIFO(st.st_mode)) return Qtrue;
1648 #endif
1649 return Qfalse;
1653 * call-seq:
1654 * File.symlink?(filepath) -> true or false
1656 * Returns +true+ if +filepath+ points to a symbolic link, +false+ otherwise:
1658 * symlink = File.symlink('t.txt', 'symlink')
1659 * File.symlink?('symlink') # => true
1660 * File.symlink?('t.txt') # => false
1664 static VALUE
1665 rb_file_symlink_p(VALUE obj, VALUE fname)
1667 #ifndef S_ISLNK
1668 # ifdef _S_ISLNK
1669 # define S_ISLNK(m) _S_ISLNK(m)
1670 # else
1671 # ifdef _S_IFLNK
1672 # define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
1673 # else
1674 # ifdef S_IFLNK
1675 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
1676 # endif
1677 # endif
1678 # endif
1679 #endif
1681 #ifdef S_ISLNK
1682 struct stat st;
1684 FilePathValue(fname);
1685 fname = rb_str_encode_ospath(fname);
1686 if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse;
1687 if (S_ISLNK(st.st_mode)) return Qtrue;
1688 #endif
1690 return Qfalse;
1694 * call-seq:
1695 * File.socket?(filepath) -> true or false
1697 * Returns +true+ if +filepath+ points to a socket, +false+ otherwise:
1699 * require 'socket'
1700 * File.socket?(Socket.new(:INET, :STREAM)) # => true
1701 * File.socket?(File.new('t.txt')) # => false
1705 static VALUE
1706 rb_file_socket_p(VALUE obj, VALUE fname)
1708 #ifndef S_ISSOCK
1709 # ifdef _S_ISSOCK
1710 # define S_ISSOCK(m) _S_ISSOCK(m)
1711 # else
1712 # ifdef _S_IFSOCK
1713 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
1714 # else
1715 # ifdef S_IFSOCK
1716 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
1717 # endif
1718 # endif
1719 # endif
1720 #endif
1722 #ifdef S_ISSOCK
1723 struct stat st;
1725 if (rb_stat(fname, &st) < 0) return Qfalse;
1726 if (S_ISSOCK(st.st_mode)) return Qtrue;
1727 #endif
1729 return Qfalse;
1733 * call-seq:
1734 * File.blockdev?(filepath) -> true or false
1736 * Returns +true+ if +filepath+ points to a block device, +false+ otherwise:
1738 * File.blockdev?('/dev/sda1') # => true
1739 * File.blockdev?(File.new('t.tmp')) # => false
1743 static VALUE
1744 rb_file_blockdev_p(VALUE obj, VALUE fname)
1746 #ifndef S_ISBLK
1747 # ifdef S_IFBLK
1748 # define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
1749 # else
1750 # define S_ISBLK(m) (0) /* anytime false */
1751 # endif
1752 #endif
1754 #ifdef S_ISBLK
1755 struct stat st;
1757 if (rb_stat(fname, &st) < 0) return Qfalse;
1758 if (S_ISBLK(st.st_mode)) return Qtrue;
1760 #endif
1761 return Qfalse;
1765 * call-seq:
1766 * File.chardev?(filepath) -> true or false
1768 * Returns +true+ if +filepath+ points to a character device, +false+ otherwise.
1770 * File.chardev?($stdin) # => true
1771 * File.chardev?('t.txt') # => false
1774 static VALUE
1775 rb_file_chardev_p(VALUE obj, VALUE fname)
1777 #ifndef S_ISCHR
1778 # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
1779 #endif
1781 struct stat st;
1783 if (rb_stat(fname, &st) < 0) return Qfalse;
1784 if (S_ISCHR(st.st_mode)) return Qtrue;
1786 return Qfalse;
1790 * call-seq:
1791 * File.exist?(file_name) -> true or false
1793 * Return <code>true</code> if the named file exists.
1795 * _file_name_ can be an IO object.
1797 * "file exists" means that stat() or fstat() system call is successful.
1800 static VALUE
1801 rb_file_exist_p(VALUE obj, VALUE fname)
1803 struct stat st;
1805 if (rb_stat(fname, &st) < 0) return Qfalse;
1806 return Qtrue;
1810 * call-seq:
1811 * File.readable?(file_name) -> true or false
1813 * Returns <code>true</code> if the named file is readable by the effective
1814 * user and group id of this process. See eaccess(3).
1816 * Note that some OS-level security features may cause this to return true
1817 * even though the file is not readable by the effective user/group.
1820 static VALUE
1821 rb_file_readable_p(VALUE obj, VALUE fname)
1823 return RBOOL(rb_eaccess(fname, R_OK) >= 0);
1827 * call-seq:
1828 * File.readable_real?(file_name) -> true or false
1830 * Returns <code>true</code> if the named file is readable by the real
1831 * user and group id of this process. See access(3).
1833 * Note that some OS-level security features may cause this to return true
1834 * even though the file is not readable by the real user/group.
1837 static VALUE
1838 rb_file_readable_real_p(VALUE obj, VALUE fname)
1840 return RBOOL(rb_access(fname, R_OK) >= 0);
1843 #ifndef S_IRUGO
1844 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1845 #endif
1847 #ifndef S_IWUGO
1848 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
1849 #endif
1852 * call-seq:
1853 * File.world_readable?(file_name) -> integer or nil
1855 * If <i>file_name</i> is readable by others, returns an integer
1856 * representing the file permission bits of <i>file_name</i>. Returns
1857 * <code>nil</code> otherwise. The meaning of the bits is platform
1858 * dependent; on Unix systems, see <code>stat(2)</code>.
1860 * _file_name_ can be an IO object.
1862 * File.world_readable?("/etc/passwd") #=> 420
1863 * m = File.world_readable?("/etc/passwd")
1864 * sprintf("%o", m) #=> "644"
1867 static VALUE
1868 rb_file_world_readable_p(VALUE obj, VALUE fname)
1870 #ifdef S_IROTH
1871 struct stat st;
1873 if (rb_stat(fname, &st) < 0) return Qnil;
1874 if ((st.st_mode & (S_IROTH)) == S_IROTH) {
1875 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1877 #endif
1878 return Qnil;
1882 * call-seq:
1883 * File.writable?(file_name) -> true or false
1885 * Returns <code>true</code> if the named file is writable by the effective
1886 * user and group id of this process. See eaccess(3).
1888 * Note that some OS-level security features may cause this to return true
1889 * even though the file is not writable by the effective user/group.
1892 static VALUE
1893 rb_file_writable_p(VALUE obj, VALUE fname)
1895 return RBOOL(rb_eaccess(fname, W_OK) >= 0);
1899 * call-seq:
1900 * File.writable_real?(file_name) -> true or false
1902 * Returns <code>true</code> if the named file is writable by the real
1903 * user and group id of this process. See access(3).
1905 * Note that some OS-level security features may cause this to return true
1906 * even though the file is not writable by the real user/group.
1909 static VALUE
1910 rb_file_writable_real_p(VALUE obj, VALUE fname)
1912 return RBOOL(rb_access(fname, W_OK) >= 0);
1916 * call-seq:
1917 * File.world_writable?(file_name) -> integer or nil
1919 * If <i>file_name</i> is writable by others, returns an integer
1920 * representing the file permission bits of <i>file_name</i>. Returns
1921 * <code>nil</code> otherwise. The meaning of the bits is platform
1922 * dependent; on Unix systems, see <code>stat(2)</code>.
1924 * _file_name_ can be an IO object.
1926 * File.world_writable?("/tmp") #=> 511
1927 * m = File.world_writable?("/tmp")
1928 * sprintf("%o", m) #=> "777"
1931 static VALUE
1932 rb_file_world_writable_p(VALUE obj, VALUE fname)
1934 #ifdef S_IWOTH
1935 struct stat st;
1937 if (rb_stat(fname, &st) < 0) return Qnil;
1938 if ((st.st_mode & (S_IWOTH)) == S_IWOTH) {
1939 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1941 #endif
1942 return Qnil;
1946 * call-seq:
1947 * File.executable?(file_name) -> true or false
1949 * Returns <code>true</code> if the named file is executable by the effective
1950 * user and group id of this process. See eaccess(3).
1952 * Windows does not support execute permissions separately from read
1953 * permissions. On Windows, a file is only considered executable if it ends in
1954 * .bat, .cmd, .com, or .exe.
1956 * Note that some OS-level security features may cause this to return true
1957 * even though the file is not executable by the effective user/group.
1960 static VALUE
1961 rb_file_executable_p(VALUE obj, VALUE fname)
1963 return RBOOL(rb_eaccess(fname, X_OK) >= 0);
1967 * call-seq:
1968 * File.executable_real?(file_name) -> true or false
1970 * Returns <code>true</code> if the named file is executable by the real
1971 * user and group id of this process. See access(3).
1973 * Windows does not support execute permissions separately from read
1974 * permissions. On Windows, a file is only considered executable if it ends in
1975 * .bat, .cmd, .com, or .exe.
1977 * Note that some OS-level security features may cause this to return true
1978 * even though the file is not executable by the real user/group.
1981 static VALUE
1982 rb_file_executable_real_p(VALUE obj, VALUE fname)
1984 return RBOOL(rb_access(fname, X_OK) >= 0);
1987 #ifndef S_ISREG
1988 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1989 #endif
1992 * call-seq:
1993 * File.file?(file) -> true or false
1995 * Returns +true+ if the named +file+ exists and is a regular file.
1997 * +file+ can be an IO object.
1999 * If the +file+ argument is a symbolic link, it will resolve the symbolic link
2000 * and use the file referenced by the link.
2003 static VALUE
2004 rb_file_file_p(VALUE obj, VALUE fname)
2006 struct stat st;
2008 if (rb_stat(fname, &st) < 0) return Qfalse;
2009 return RBOOL(S_ISREG(st.st_mode));
2013 * call-seq:
2014 * File.zero?(file_name) -> true or false
2016 * Returns <code>true</code> if the named file exists and has
2017 * a zero size.
2019 * _file_name_ can be an IO object.
2022 static VALUE
2023 rb_file_zero_p(VALUE obj, VALUE fname)
2025 struct stat st;
2027 if (rb_stat(fname, &st) < 0) return Qfalse;
2028 return RBOOL(st.st_size == 0);
2032 * call-seq:
2033 * File.size?(file_name) -> Integer or nil
2035 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
2036 * file otherwise.
2038 * _file_name_ can be an IO object.
2041 static VALUE
2042 rb_file_size_p(VALUE obj, VALUE fname)
2044 struct stat st;
2046 if (rb_stat(fname, &st) < 0) return Qnil;
2047 if (st.st_size == 0) return Qnil;
2048 return OFFT2NUM(st.st_size);
2052 * call-seq:
2053 * File.owned?(file_name) -> true or false
2055 * Returns <code>true</code> if the named file exists and the
2056 * effective used id of the calling process is the owner of
2057 * the file.
2059 * _file_name_ can be an IO object.
2062 static VALUE
2063 rb_file_owned_p(VALUE obj, VALUE fname)
2065 struct stat st;
2067 if (rb_stat(fname, &st) < 0) return Qfalse;
2068 return RBOOL(st.st_uid == geteuid());
2071 static VALUE
2072 rb_file_rowned_p(VALUE obj, VALUE fname)
2074 struct stat st;
2076 if (rb_stat(fname, &st) < 0) return Qfalse;
2077 return RBOOL(st.st_uid == getuid());
2081 * call-seq:
2082 * File.grpowned?(file_name) -> true or false
2084 * Returns <code>true</code> if the named file exists and the
2085 * effective group id of the calling process is the owner of
2086 * the file. Returns <code>false</code> on Windows.
2088 * _file_name_ can be an IO object.
2091 static VALUE
2092 rb_file_grpowned_p(VALUE obj, VALUE fname)
2094 #ifndef _WIN32
2095 struct stat st;
2097 if (rb_stat(fname, &st) < 0) return Qfalse;
2098 if (rb_group_member(st.st_gid)) return Qtrue;
2099 #endif
2100 return Qfalse;
2103 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2104 static VALUE
2105 check3rdbyte(VALUE fname, int mode)
2107 struct stat st;
2109 if (rb_stat(fname, &st) < 0) return Qfalse;
2110 return RBOOL(st.st_mode & mode);
2112 #endif
2115 * call-seq:
2116 * File.setuid?(file_name) -> true or false
2118 * Returns <code>true</code> if the named file has the setuid bit set.
2120 * _file_name_ can be an IO object.
2123 static VALUE
2124 rb_file_suid_p(VALUE obj, VALUE fname)
2126 #ifdef S_ISUID
2127 return check3rdbyte(fname, S_ISUID);
2128 #else
2129 return Qfalse;
2130 #endif
2134 * call-seq:
2135 * File.setgid?(file_name) -> true or false
2137 * Returns <code>true</code> if the named file has the setgid bit set.
2139 * _file_name_ can be an IO object.
2142 static VALUE
2143 rb_file_sgid_p(VALUE obj, VALUE fname)
2145 #ifdef S_ISGID
2146 return check3rdbyte(fname, S_ISGID);
2147 #else
2148 return Qfalse;
2149 #endif
2153 * call-seq:
2154 * File.sticky?(file_name) -> true or false
2156 * Returns <code>true</code> if the named file has the sticky bit set.
2158 * _file_name_ can be an IO object.
2161 static VALUE
2162 rb_file_sticky_p(VALUE obj, VALUE fname)
2164 #ifdef S_ISVTX
2165 return check3rdbyte(fname, S_ISVTX);
2166 #else
2167 return Qfalse;
2168 #endif
2172 * call-seq:
2173 * File.identical?(file_1, file_2) -> true or false
2175 * Returns <code>true</code> if the named files are identical.
2177 * _file_1_ and _file_2_ can be an IO object.
2179 * open("a", "w") {}
2180 * p File.identical?("a", "a") #=> true
2181 * p File.identical?("a", "./a") #=> true
2182 * File.link("a", "b")
2183 * p File.identical?("a", "b") #=> true
2184 * File.symlink("a", "c")
2185 * p File.identical?("a", "c") #=> true
2186 * open("d", "w") {}
2187 * p File.identical?("a", "d") #=> false
2190 static VALUE
2191 rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2)
2193 #ifndef _WIN32
2194 struct stat st1, st2;
2196 if (rb_stat(fname1, &st1) < 0) return Qfalse;
2197 if (rb_stat(fname2, &st2) < 0) return Qfalse;
2198 if (st1.st_dev != st2.st_dev) return Qfalse;
2199 if (st1.st_ino != st2.st_ino) return Qfalse;
2200 return Qtrue;
2201 #else
2202 extern VALUE rb_w32_file_identical_p(VALUE, VALUE);
2203 return rb_w32_file_identical_p(fname1, fname2);
2204 #endif
2208 * call-seq:
2209 * File.size(file_name) -> integer
2211 * Returns the size of <code>file_name</code>.
2213 * _file_name_ can be an IO object.
2216 static VALUE
2217 rb_file_s_size(VALUE klass, VALUE fname)
2219 struct stat st;
2221 if (rb_stat(fname, &st) < 0) {
2222 int e = errno;
2223 FilePathValue(fname);
2224 rb_syserr_fail_path(e, fname);
2226 return OFFT2NUM(st.st_size);
2229 static VALUE
2230 rb_file_ftype(const struct stat *st)
2232 const char *t;
2234 if (S_ISREG(st->st_mode)) {
2235 t = "file";
2237 else if (S_ISDIR(st->st_mode)) {
2238 t = "directory";
2240 else if (S_ISCHR(st->st_mode)) {
2241 t = "characterSpecial";
2243 #ifdef S_ISBLK
2244 else if (S_ISBLK(st->st_mode)) {
2245 t = "blockSpecial";
2247 #endif
2248 #ifdef S_ISFIFO
2249 else if (S_ISFIFO(st->st_mode)) {
2250 t = "fifo";
2252 #endif
2253 #ifdef S_ISLNK
2254 else if (S_ISLNK(st->st_mode)) {
2255 t = "link";
2257 #endif
2258 #ifdef S_ISSOCK
2259 else if (S_ISSOCK(st->st_mode)) {
2260 t = "socket";
2262 #endif
2263 else {
2264 t = "unknown";
2267 return rb_usascii_str_new2(t);
2271 * call-seq:
2272 * File.ftype(file_name) -> string
2274 * Identifies the type of the named file; the return string is one of
2275 * ``<code>file</code>'', ``<code>directory</code>'',
2276 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
2277 * ``<code>fifo</code>'', ``<code>link</code>'',
2278 * ``<code>socket</code>'', or ``<code>unknown</code>''.
2280 * File.ftype("testfile") #=> "file"
2281 * File.ftype("/dev/tty") #=> "characterSpecial"
2282 * File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2285 static VALUE
2286 rb_file_s_ftype(VALUE klass, VALUE fname)
2288 struct stat st;
2290 FilePathValue(fname);
2291 fname = rb_str_encode_ospath(fname);
2292 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
2293 rb_sys_fail_path(fname);
2296 return rb_file_ftype(&st);
2300 * call-seq:
2301 * File.atime(file_name) -> time
2303 * Returns the last access time for the named file as a Time object.
2305 * _file_name_ can be an IO object.
2307 * File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2311 static VALUE
2312 rb_file_s_atime(VALUE klass, VALUE fname)
2314 struct stat st;
2316 if (rb_stat(fname, &st) < 0) {
2317 int e = errno;
2318 FilePathValue(fname);
2319 rb_syserr_fail_path(e, fname);
2321 return stat_atime(&st);
2325 * call-seq:
2326 * file.atime -> time
2328 * Returns the last access time (a Time object) for <i>file</i>, or
2329 * epoch if <i>file</i> has not been accessed.
2331 * File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2335 static VALUE
2336 rb_file_atime(VALUE obj)
2338 rb_io_t *fptr;
2339 struct stat st;
2341 GetOpenFile(obj, fptr);
2342 if (fstat(fptr->fd, &st) == -1) {
2343 rb_sys_fail_path(fptr->pathv);
2345 return stat_atime(&st);
2349 * call-seq:
2350 * File.mtime(file_name) -> time
2352 * Returns the modification time for the named file as a Time object.
2354 * _file_name_ can be an IO object.
2356 * File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2360 static VALUE
2361 rb_file_s_mtime(VALUE klass, VALUE fname)
2363 struct stat st;
2365 if (rb_stat(fname, &st) < 0) {
2366 int e = errno;
2367 FilePathValue(fname);
2368 rb_syserr_fail_path(e, fname);
2370 return stat_mtime(&st);
2374 * call-seq:
2375 * file.mtime -> time
2377 * Returns the modification time for <i>file</i>.
2379 * File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2383 static VALUE
2384 rb_file_mtime(VALUE obj)
2386 rb_io_t *fptr;
2387 struct stat st;
2389 GetOpenFile(obj, fptr);
2390 if (fstat(fptr->fd, &st) == -1) {
2391 rb_sys_fail_path(fptr->pathv);
2393 return stat_mtime(&st);
2397 * call-seq:
2398 * File.ctime(file_name) -> time
2400 * Returns the change time for the named file (the time at which
2401 * directory information about the file was changed, not the file
2402 * itself).
2404 * _file_name_ can be an IO object.
2406 * Note that on Windows (NTFS), returns creation time (birth time).
2408 * File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2412 static VALUE
2413 rb_file_s_ctime(VALUE klass, VALUE fname)
2415 struct stat st;
2417 if (rb_stat(fname, &st) < 0) {
2418 int e = errno;
2419 FilePathValue(fname);
2420 rb_syserr_fail_path(e, fname);
2422 return stat_ctime(&st);
2426 * call-seq:
2427 * file.ctime -> time
2429 * Returns the change time for <i>file</i> (that is, the time directory
2430 * information about the file was changed, not the file itself).
2432 * Note that on Windows (NTFS), returns creation time (birth time).
2434 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2438 static VALUE
2439 rb_file_ctime(VALUE obj)
2441 rb_io_t *fptr;
2442 struct stat st;
2444 GetOpenFile(obj, fptr);
2445 if (fstat(fptr->fd, &st) == -1) {
2446 rb_sys_fail_path(fptr->pathv);
2448 return stat_ctime(&st);
2451 #if defined(HAVE_STAT_BIRTHTIME)
2453 * call-seq:
2454 * File.birthtime(file_name) -> time
2456 * Returns the birth time for the named file.
2458 * _file_name_ can be an IO object.
2460 * File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2462 * If the platform doesn't have birthtime, raises NotImplementedError.
2466 VALUE
2467 rb_file_s_birthtime(VALUE klass, VALUE fname)
2469 statx_data st;
2471 if (rb_statx(fname, &st, STATX_BTIME) < 0) {
2472 int e = errno;
2473 FilePathValue(fname);
2474 rb_syserr_fail_path(e, fname);
2476 return statx_birthtime(&st, fname);
2478 #else
2479 # define rb_file_s_birthtime rb_f_notimplement
2480 #endif
2482 #if defined(HAVE_STAT_BIRTHTIME)
2484 * call-seq:
2485 * file.birthtime -> time
2487 * Returns the birth time for <i>file</i>.
2489 * File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
2491 * If the platform doesn't have birthtime, raises NotImplementedError.
2495 static VALUE
2496 rb_file_birthtime(VALUE obj)
2498 rb_io_t *fptr;
2499 statx_data st;
2501 GetOpenFile(obj, fptr);
2502 if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) {
2503 rb_sys_fail_path(fptr->pathv);
2505 return statx_birthtime(&st, fptr->pathv);
2507 #else
2508 # define rb_file_birthtime rb_f_notimplement
2509 #endif
2511 rb_off_t
2512 rb_file_size(VALUE file)
2514 if (RB_TYPE_P(file, T_FILE)) {
2515 rb_io_t *fptr;
2516 struct stat st;
2518 RB_IO_POINTER(file, fptr);
2519 if (fptr->mode & FMODE_WRITABLE) {
2520 rb_io_flush_raw(file, 0);
2523 if (fstat(fptr->fd, &st) == -1) {
2524 rb_sys_fail_path(fptr->pathv);
2527 return st.st_size;
2529 else {
2530 return NUM2OFFT(rb_funcall(file, idSize, 0));
2535 * call-seq:
2536 * file.size -> integer
2538 * Returns the size of <i>file</i> in bytes.
2540 * File.new("testfile").size #=> 66
2544 static VALUE
2545 file_size(VALUE self)
2547 return OFFT2NUM(rb_file_size(self));
2550 struct nogvl_chmod_data {
2551 const char *path;
2552 mode_t mode;
2555 static void *
2556 nogvl_chmod(void *ptr)
2558 struct nogvl_chmod_data *data = ptr;
2559 int ret = chmod(data->path, data->mode);
2560 return (void *)(VALUE)ret;
2563 static int
2564 rb_chmod(const char *path, mode_t mode)
2566 struct nogvl_chmod_data data = {
2567 .path = path,
2568 .mode = mode,
2570 return IO_WITHOUT_GVL_INT(nogvl_chmod, &data);
2573 static int
2574 chmod_internal(const char *path, void *mode)
2576 return chmod(path, *(mode_t *)mode);
2580 * call-seq:
2581 * File.chmod(mode_int, file_name, ... ) -> integer
2583 * Changes permission bits on the named file(s) to the bit pattern
2584 * represented by <i>mode_int</i>. Actual effects are operating system
2585 * dependent (see the beginning of this section). On Unix systems, see
2586 * <code>chmod(2)</code> for details. Returns the number of files
2587 * processed.
2589 * File.chmod(0644, "testfile", "out") #=> 2
2592 static VALUE
2593 rb_file_s_chmod(int argc, VALUE *argv, VALUE _)
2595 mode_t mode;
2597 apply2args(1);
2598 mode = NUM2MODET(*argv++);
2600 return apply2files(chmod_internal, argc, argv, &mode);
2603 #ifdef HAVE_FCHMOD
2604 struct nogvl_fchmod_data {
2605 int fd;
2606 mode_t mode;
2609 static VALUE
2610 io_blocking_fchmod(void *ptr)
2612 struct nogvl_fchmod_data *data = ptr;
2613 int ret = fchmod(data->fd, data->mode);
2614 return (VALUE)ret;
2617 static int
2618 rb_fchmod(int fd, mode_t mode)
2620 (void)rb_chmod; /* suppress unused-function warning when HAVE_FCHMOD */
2621 struct nogvl_fchmod_data data = {.fd = fd, .mode = mode};
2622 return (int)rb_thread_io_blocking_region(io_blocking_fchmod, &data, fd);
2624 #endif
2627 * call-seq:
2628 * file.chmod(mode_int) -> 0
2630 * Changes permission bits on <i>file</i> to the bit pattern
2631 * represented by <i>mode_int</i>. Actual effects are platform
2632 * dependent; on Unix systems, see <code>chmod(2)</code> for details.
2633 * Follows symbolic links. Also see File#lchmod.
2635 * f = File.new("out", "w");
2636 * f.chmod(0644) #=> 0
2639 static VALUE
2640 rb_file_chmod(VALUE obj, VALUE vmode)
2642 rb_io_t *fptr;
2643 mode_t mode;
2644 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2645 VALUE path;
2646 #endif
2648 mode = NUM2MODET(vmode);
2650 GetOpenFile(obj, fptr);
2651 #ifdef HAVE_FCHMOD
2652 if (rb_fchmod(fptr->fd, mode) == -1) {
2653 if (HAVE_FCHMOD || errno != ENOSYS)
2654 rb_sys_fail_path(fptr->pathv);
2656 else {
2657 if (!HAVE_FCHMOD) return INT2FIX(0);
2659 #endif
2660 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2661 if (NIL_P(fptr->pathv)) return Qnil;
2662 path = rb_str_encode_ospath(fptr->pathv);
2663 if (rb_chmod(RSTRING_PTR(path), mode) == -1)
2664 rb_sys_fail_path(fptr->pathv);
2665 #endif
2667 return INT2FIX(0);
2670 #if defined(HAVE_LCHMOD)
2671 static int
2672 lchmod_internal(const char *path, void *mode)
2674 return lchmod(path, *(mode_t *)mode);
2678 * call-seq:
2679 * File.lchmod(mode_int, file_name, ...) -> integer
2681 * Equivalent to File::chmod, but does not follow symbolic links (so
2682 * it will change the permissions associated with the link, not the
2683 * file referenced by the link). Often not available.
2687 static VALUE
2688 rb_file_s_lchmod(int argc, VALUE *argv, VALUE _)
2690 mode_t mode;
2692 apply2args(1);
2693 mode = NUM2MODET(*argv++);
2695 return apply2files(lchmod_internal, argc, argv, &mode);
2697 #else
2698 #define rb_file_s_lchmod rb_f_notimplement
2699 #endif
2701 static inline rb_uid_t
2702 to_uid(VALUE u)
2704 if (NIL_P(u)) {
2705 return (rb_uid_t)-1;
2707 return NUM2UIDT(u);
2710 static inline rb_gid_t
2711 to_gid(VALUE g)
2713 if (NIL_P(g)) {
2714 return (rb_gid_t)-1;
2716 return NUM2GIDT(g);
2719 struct chown_args {
2720 rb_uid_t owner;
2721 rb_gid_t group;
2724 static int
2725 chown_internal(const char *path, void *arg)
2727 struct chown_args *args = arg;
2728 return chown(path, args->owner, args->group);
2732 * call-seq:
2733 * File.chown(owner_int, group_int, file_name, ...) -> integer
2735 * Changes the owner and group of the named file(s) to the given
2736 * numeric owner and group id's. Only a process with superuser
2737 * privileges may change the owner of a file. The current owner of a
2738 * file may change the file's group to any group to which the owner
2739 * belongs. A <code>nil</code> or -1 owner or group id is ignored.
2740 * Returns the number of files processed.
2742 * File.chown(nil, 100, "testfile")
2746 static VALUE
2747 rb_file_s_chown(int argc, VALUE *argv, VALUE _)
2749 struct chown_args arg;
2751 apply2args(2);
2752 arg.owner = to_uid(*argv++);
2753 arg.group = to_gid(*argv++);
2755 return apply2files(chown_internal, argc, argv, &arg);
2758 struct nogvl_chown_data {
2759 union {
2760 const char *path;
2761 int fd;
2762 } as;
2763 struct chown_args new;
2766 static void *
2767 nogvl_chown(void *ptr)
2769 struct nogvl_chown_data *data = ptr;
2770 return (void *)(VALUE)chown(data->as.path, data->new.owner, data->new.group);
2773 static int
2774 rb_chown(const char *path, rb_uid_t owner, rb_gid_t group)
2776 struct nogvl_chown_data data = {
2777 .as = {.path = path},
2778 .new = {.owner = owner, .group = group},
2780 return IO_WITHOUT_GVL_INT(nogvl_chown, &data);
2783 #ifdef HAVE_FCHOWN
2784 static void *
2785 nogvl_fchown(void *ptr)
2787 struct nogvl_chown_data *data = ptr;
2788 return (void *)(VALUE)fchown(data->as.fd, data->new.owner, data->new.group);
2791 static int
2792 rb_fchown(int fd, rb_uid_t owner, rb_gid_t group)
2794 (void)rb_chown; /* suppress unused-function warning when HAVE_FCHMOD */
2795 struct nogvl_chown_data data = {
2796 .as = {.fd = fd},
2797 .new = {.owner = owner, .group = group},
2799 return IO_WITHOUT_GVL_INT(nogvl_fchown, &data);
2801 #endif
2804 * call-seq:
2805 * file.chown(owner_int, group_int ) -> 0
2807 * Changes the owner and group of <i>file</i> to the given numeric
2808 * owner and group id's. Only a process with superuser privileges may
2809 * change the owner of a file. The current owner of a file may change
2810 * the file's group to any group to which the owner belongs. A
2811 * <code>nil</code> or -1 owner or group id is ignored. Follows
2812 * symbolic links. See also File#lchown.
2814 * File.new("testfile").chown(502, 1000)
2818 static VALUE
2819 rb_file_chown(VALUE obj, VALUE owner, VALUE group)
2821 rb_io_t *fptr;
2822 rb_uid_t o;
2823 rb_gid_t g;
2824 #ifndef HAVE_FCHOWN
2825 VALUE path;
2826 #endif
2828 o = to_uid(owner);
2829 g = to_gid(group);
2830 GetOpenFile(obj, fptr);
2831 #ifndef HAVE_FCHOWN
2832 if (NIL_P(fptr->pathv)) return Qnil;
2833 path = rb_str_encode_ospath(fptr->pathv);
2834 if (rb_chown(RSTRING_PTR(path), o, g) == -1)
2835 rb_sys_fail_path(fptr->pathv);
2836 #else
2837 if (rb_fchown(fptr->fd, o, g) == -1)
2838 rb_sys_fail_path(fptr->pathv);
2839 #endif
2841 return INT2FIX(0);
2844 #if defined(HAVE_LCHOWN)
2845 static int
2846 lchown_internal(const char *path, void *arg)
2848 struct chown_args *args = arg;
2849 return lchown(path, args->owner, args->group);
2853 * call-seq:
2854 * File.lchown(owner_int, group_int, file_name,..) -> integer
2856 * Equivalent to File::chown, but does not follow symbolic
2857 * links (so it will change the owner associated with the link, not the
2858 * file referenced by the link). Often not available. Returns number
2859 * of files in the argument list.
2863 static VALUE
2864 rb_file_s_lchown(int argc, VALUE *argv, VALUE _)
2866 struct chown_args arg;
2868 apply2args(2);
2869 arg.owner = to_uid(*argv++);
2870 arg.group = to_gid(*argv++);
2872 return apply2files(lchown_internal, argc, argv, &arg);
2874 #else
2875 #define rb_file_s_lchown rb_f_notimplement
2876 #endif
2878 struct utime_args {
2879 const struct timespec* tsp;
2880 VALUE atime, mtime;
2881 int follow; /* Whether to act on symlinks (1) or their referent (0) */
2884 #ifdef UTIME_EINVAL
2885 NORETURN(static void utime_failed(struct apply_arg *));
2887 static void
2888 utime_failed(struct apply_arg *aa)
2890 int e = aa->errnum;
2891 VALUE path = aa->fn[aa->i].path;
2892 struct utime_args *ua = aa->arg;
2894 if (ua->tsp && e == EINVAL) {
2895 VALUE e[2], a = Qnil, m = Qnil;
2896 int d = 0;
2897 VALUE atime = ua->atime;
2898 VALUE mtime = ua->mtime;
2900 if (!NIL_P(atime)) {
2901 a = rb_inspect(atime);
2903 if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) {
2904 m = rb_inspect(mtime);
2906 if (NIL_P(a)) e[0] = m;
2907 else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a;
2908 else {
2909 e[0] = rb_str_plus(a, rb_str_new_cstr(" or "));
2910 rb_str_append(e[0], m);
2911 d = 1;
2913 if (!NIL_P(e[0])) {
2914 if (path) {
2915 if (!d) e[0] = rb_str_dup(e[0]);
2916 rb_str_append(rb_str_cat2(e[0], " for "), path);
2918 e[1] = INT2FIX(EINVAL);
2919 rb_exc_raise(rb_class_new_instance(2, e, rb_eSystemCallError));
2922 rb_syserr_fail_path(e, path);
2924 #endif /* UTIME_EINVAL */
2926 #if defined(HAVE_UTIMES)
2928 # if !defined(HAVE_UTIMENSAT)
2929 /* utimensat() is not found, runtime check is not needed */
2930 # elif defined(__APPLE__) && \
2931 (!defined(MAC_OS_X_VERSION_13_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_13_0))
2933 # if defined(__has_attribute) && __has_attribute(availability)
2934 typedef int utimensat_func(int, const char *, const struct timespec [2], int);
2936 RBIMPL_WARNING_PUSH()
2937 RBIMPL_WARNING_IGNORED(-Wunguarded-availability-new)
2938 static inline utimensat_func *
2939 rb_utimensat(void)
2941 return &utimensat;
2943 RBIMPL_WARNING_POP()
2945 # define utimensat rb_utimensat()
2946 # else /* __API_AVAILABLE macro does nothing on gcc */
2947 __attribute__((weak)) int utimensat(int, const char *, const struct timespec [2], int);
2948 # endif /* defined(__has_attribute) && __has_attribute(availability) */
2949 # endif /* __APPLE__ && < MAC_OS_X_VERSION_13_0 */
2951 static int
2952 utime_internal(const char *path, void *arg)
2954 struct utime_args *v = arg;
2955 const struct timespec *tsp = v->tsp;
2956 struct timeval tvbuf[2], *tvp = NULL;
2958 #if defined(HAVE_UTIMENSAT)
2959 # if defined(__APPLE__)
2960 const int try_utimensat = utimensat != NULL;
2961 const int try_utimensat_follow = utimensat != NULL;
2962 # else /* !__APPLE__ */
2963 # define TRY_UTIMENSAT 1
2964 static int try_utimensat = 1;
2965 # ifdef AT_SYMLINK_NOFOLLOW
2966 static int try_utimensat_follow = 1;
2967 # else
2968 const int try_utimensat_follow = 0;
2969 # endif
2970 # endif /* __APPLE__ */
2971 int flags = 0;
2973 if (v->follow ? try_utimensat_follow : try_utimensat) {
2974 # ifdef AT_SYMLINK_NOFOLLOW
2975 if (v->follow) {
2976 flags = AT_SYMLINK_NOFOLLOW;
2978 # endif
2980 int result = utimensat(AT_FDCWD, path, tsp, flags);
2981 # ifdef TRY_UTIMENSAT
2982 if (result < 0 && errno == ENOSYS) {
2983 # ifdef AT_SYMLINK_NOFOLLOW
2984 try_utimensat_follow = 0;
2985 # endif /* AT_SYMLINK_NOFOLLOW */
2986 if (!v->follow)
2987 try_utimensat = 0;
2989 else
2990 # endif /* TRY_UTIMESAT */
2991 return result;
2993 #endif /* defined(HAVE_UTIMENSAT) */
2995 if (tsp) {
2996 tvbuf[0].tv_sec = tsp[0].tv_sec;
2997 tvbuf[0].tv_usec = (int)(tsp[0].tv_nsec / 1000);
2998 tvbuf[1].tv_sec = tsp[1].tv_sec;
2999 tvbuf[1].tv_usec = (int)(tsp[1].tv_nsec / 1000);
3000 tvp = tvbuf;
3002 #ifdef HAVE_LUTIMES
3003 if (v->follow) return lutimes(path, tvp);
3004 #endif
3005 return utimes(path, tvp);
3008 #else /* !defined(HAVE_UTIMES) */
3010 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
3011 struct utimbuf {
3012 long actime;
3013 long modtime;
3015 #endif
3017 static int
3018 utime_internal(const char *path, void *arg)
3020 struct utime_args *v = arg;
3021 const struct timespec *tsp = v->tsp;
3022 struct utimbuf utbuf, *utp = NULL;
3023 if (tsp) {
3024 utbuf.actime = tsp[0].tv_sec;
3025 utbuf.modtime = tsp[1].tv_sec;
3026 utp = &utbuf;
3028 return utime(path, utp);
3030 #endif /* !defined(HAVE_UTIMES) */
3032 static VALUE
3033 utime_internal_i(int argc, VALUE *argv, int follow)
3035 struct utime_args args;
3036 struct timespec tss[2], *tsp = NULL;
3038 apply2args(2);
3039 args.atime = *argv++;
3040 args.mtime = *argv++;
3042 args.follow = follow;
3044 if (!NIL_P(args.atime) || !NIL_P(args.mtime)) {
3045 tsp = tss;
3046 tsp[0] = rb_time_timespec(args.atime);
3047 if (args.atime == args.mtime)
3048 tsp[1] = tsp[0];
3049 else
3050 tsp[1] = rb_time_timespec(args.mtime);
3052 args.tsp = tsp;
3054 return apply2files(utime_internal, argc, argv, &args);
3058 * call-seq:
3059 * File.utime(atime, mtime, file_name, ...) -> integer
3061 * Sets the access and modification times of each named file to the
3062 * first two arguments. If a file is a symlink, this method acts upon
3063 * its referent rather than the link itself; for the inverse
3064 * behavior see File.lutime. Returns the number of file
3065 * names in the argument list.
3068 static VALUE
3069 rb_file_s_utime(int argc, VALUE *argv, VALUE _)
3071 return utime_internal_i(argc, argv, FALSE);
3074 #if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
3077 * call-seq:
3078 * File.lutime(atime, mtime, file_name, ...) -> integer
3080 * Sets the access and modification times of each named file to the
3081 * first two arguments. If a file is a symlink, this method acts upon
3082 * the link itself as opposed to its referent; for the inverse
3083 * behavior, see File.utime. Returns the number of file
3084 * names in the argument list.
3087 static VALUE
3088 rb_file_s_lutime(int argc, VALUE *argv, VALUE _)
3090 return utime_internal_i(argc, argv, TRUE);
3092 #else
3093 #define rb_file_s_lutime rb_f_notimplement
3094 #endif
3096 #ifdef RUBY_FUNCTION_NAME_STRING
3097 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
3098 #else
3099 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
3100 #endif
3101 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
3102 NORETURN(static void syserr_fail2_in(const char *,int,VALUE,VALUE));
3103 static void
3104 syserr_fail2_in(const char *func, int e, VALUE s1, VALUE s2)
3106 VALUE str;
3107 #ifdef MAX_PATH
3108 const int max_pathlen = MAX_PATH;
3109 #else
3110 const int max_pathlen = MAXPATHLEN;
3111 #endif
3113 if (e == EEXIST) {
3114 rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen));
3116 str = rb_str_new_cstr("(");
3117 rb_str_append(str, rb_str_ellipsize(s1, max_pathlen));
3118 rb_str_cat2(str, ", ");
3119 rb_str_append(str, rb_str_ellipsize(s2, max_pathlen));
3120 rb_str_cat2(str, ")");
3121 #ifdef RUBY_FUNCTION_NAME_STRING
3122 rb_syserr_fail_path_in(func, e, str);
3123 #else
3124 rb_syserr_fail_path(e, str);
3125 #endif
3128 #ifdef HAVE_LINK
3130 * call-seq:
3131 * File.link(old_name, new_name) -> 0
3133 * Creates a new name for an existing file using a hard link. Will not
3134 * overwrite <i>new_name</i> if it already exists (raising a subclass
3135 * of SystemCallError). Not available on all platforms.
3137 * File.link("testfile", ".testfile") #=> 0
3138 * IO.readlines(".testfile")[0] #=> "This is line one\n"
3141 static VALUE
3142 rb_file_s_link(VALUE klass, VALUE from, VALUE to)
3144 FilePathValue(from);
3145 FilePathValue(to);
3146 from = rb_str_encode_ospath(from);
3147 to = rb_str_encode_ospath(to);
3149 if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
3150 sys_fail2(from, to);
3152 return INT2FIX(0);
3154 #else
3155 #define rb_file_s_link rb_f_notimplement
3156 #endif
3158 #ifdef HAVE_SYMLINK
3160 * call-seq:
3161 * File.symlink(old_name, new_name) -> 0
3163 * Creates a symbolic link called <i>new_name</i> for the existing file
3164 * <i>old_name</i>. Raises a NotImplemented exception on
3165 * platforms that do not support symbolic links.
3167 * File.symlink("testfile", "link2test") #=> 0
3171 static VALUE
3172 rb_file_s_symlink(VALUE klass, VALUE from, VALUE to)
3174 FilePathValue(from);
3175 FilePathValue(to);
3176 from = rb_str_encode_ospath(from);
3177 to = rb_str_encode_ospath(to);
3179 if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
3180 sys_fail2(from, to);
3182 return INT2FIX(0);
3184 #else
3185 #define rb_file_s_symlink rb_f_notimplement
3186 #endif
3188 #ifdef HAVE_READLINK
3190 * call-seq:
3191 * File.readlink(link_name) -> file_name
3193 * Returns the name of the file referenced by the given link.
3194 * Not available on all platforms.
3196 * File.symlink("testfile", "link2test") #=> 0
3197 * File.readlink("link2test") #=> "testfile"
3200 static VALUE
3201 rb_file_s_readlink(VALUE klass, VALUE path)
3203 return rb_readlink(path, rb_filesystem_encoding());
3206 struct readlink_arg {
3207 const char *path;
3208 char *buf;
3209 size_t size;
3212 static void *
3213 nogvl_readlink(void *ptr)
3215 struct readlink_arg *ra = ptr;
3217 return (void *)(VALUE)readlink(ra->path, ra->buf, ra->size);
3220 static ssize_t
3221 readlink_without_gvl(VALUE path, VALUE buf, size_t size)
3223 struct readlink_arg ra;
3225 ra.path = RSTRING_PTR(path);
3226 ra.buf = RSTRING_PTR(buf);
3227 ra.size = size;
3229 return (ssize_t)IO_WITHOUT_GVL(nogvl_readlink, &ra);
3232 VALUE
3233 rb_readlink(VALUE path, rb_encoding *enc)
3235 int size = 100;
3236 ssize_t rv;
3237 VALUE v;
3239 FilePathValue(path);
3240 path = rb_str_encode_ospath(path);
3241 v = rb_enc_str_new(0, size, enc);
3242 while ((rv = readlink_without_gvl(path, v, size)) == size
3243 #ifdef _AIX
3244 || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
3245 #endif
3247 rb_str_modify_expand(v, size);
3248 size *= 2;
3249 rb_str_set_len(v, size);
3251 if (rv < 0) {
3252 int e = errno;
3253 rb_str_resize(v, 0);
3254 rb_syserr_fail_path(e, path);
3256 rb_str_resize(v, rv);
3258 return v;
3260 #else
3261 #define rb_file_s_readlink rb_f_notimplement
3262 #endif
3264 static int
3265 unlink_internal(const char *path, void *arg)
3267 return unlink(path);
3271 * call-seq:
3272 * File.delete(file_name, ...) -> integer
3273 * File.unlink(file_name, ...) -> integer
3275 * Deletes the named files, returning the number of names
3276 * passed as arguments. Raises an exception on any error.
3277 * Since the underlying implementation relies on the
3278 * <code>unlink(2)</code> system call, the type of
3279 * exception raised depends on its error type (see
3280 * https://linux.die.net/man/2/unlink) and has the form of
3281 * e.g. Errno::ENOENT.
3283 * See also Dir::rmdir.
3286 static VALUE
3287 rb_file_s_unlink(int argc, VALUE *argv, VALUE klass)
3289 return apply2files(unlink_internal, argc, argv, 0);
3292 struct rename_args {
3293 const char *src;
3294 const char *dst;
3297 static void *
3298 no_gvl_rename(void *ptr)
3300 struct rename_args *ra = ptr;
3302 return (void *)(VALUE)rename(ra->src, ra->dst);
3306 * call-seq:
3307 * File.rename(old_name, new_name) -> 0
3309 * Renames the given file to the new name. Raises a SystemCallError
3310 * if the file cannot be renamed.
3312 * File.rename("afile", "afile.bak") #=> 0
3315 static VALUE
3316 rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
3318 struct rename_args ra;
3319 VALUE f, t;
3321 FilePathValue(from);
3322 FilePathValue(to);
3323 f = rb_str_encode_ospath(from);
3324 t = rb_str_encode_ospath(to);
3325 ra.src = StringValueCStr(f);
3326 ra.dst = StringValueCStr(t);
3327 #if defined __CYGWIN__
3328 errno = 0;
3329 #endif
3330 if (IO_WITHOUT_GVL_INT(no_gvl_rename, &ra) < 0) {
3331 int e = errno;
3332 #if defined DOSISH
3333 switch (e) {
3334 case EEXIST:
3335 if (chmod(ra.dst, 0666) == 0 &&
3336 unlink(ra.dst) == 0 &&
3337 rename(ra.src, ra.dst) == 0)
3338 return INT2FIX(0);
3340 #endif
3341 syserr_fail2(e, from, to);
3344 return INT2FIX(0);
3348 * call-seq:
3349 * File.umask() -> integer
3350 * File.umask(integer) -> integer
3352 * Returns the current umask value for this process. If the optional
3353 * argument is given, set the umask to that value and return the
3354 * previous value. Umask values are <em>subtracted</em> from the
3355 * default permissions, so a umask of <code>0222</code> would make a
3356 * file read-only for everyone.
3358 * File.umask(0006) #=> 18
3359 * File.umask #=> 6
3362 static VALUE
3363 rb_file_s_umask(int argc, VALUE *argv, VALUE _)
3365 mode_t omask = 0;
3367 switch (argc) {
3368 case 0:
3369 omask = umask(0);
3370 umask(omask);
3371 break;
3372 case 1:
3373 omask = umask(NUM2MODET(argv[0]));
3374 break;
3375 default:
3376 rb_error_arity(argc, 0, 1);
3378 return MODET2NUM(omask);
3381 #ifdef __CYGWIN__
3382 #undef DOSISH
3383 #endif
3384 #if defined __CYGWIN__ || defined DOSISH
3385 #define DOSISH_UNC
3386 #define DOSISH_DRIVE_LETTER
3387 #define FILE_ALT_SEPARATOR '\\'
3388 #endif
3389 #ifdef FILE_ALT_SEPARATOR
3390 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3391 # ifdef DOSISH
3392 static const char file_alt_separator[] = {FILE_ALT_SEPARATOR, '\0'};
3393 # endif
3394 #else
3395 #define isdirsep(x) ((x) == '/')
3396 #endif
3398 #ifndef USE_NTFS
3399 # if defined _WIN32
3400 # define USE_NTFS 1
3401 # else
3402 # define USE_NTFS 0
3403 # endif
3404 #endif
3406 #ifndef USE_NTFS_ADS
3407 # if USE_NTFS
3408 # define USE_NTFS_ADS 1
3409 # else
3410 # define USE_NTFS_ADS 0
3411 # endif
3412 #endif
3414 #if USE_NTFS
3415 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3416 #else
3417 #define istrailinggarbage(x) 0
3418 #endif
3420 #if USE_NTFS_ADS
3421 # define isADS(x) ((x) == ':')
3422 #else
3423 # define isADS(x) 0
3424 #endif
3426 #define Next(p, e, enc) ((p) + rb_enc_mbclen((p), (e), (enc)))
3427 #define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
3429 #if defined(DOSISH_UNC)
3430 #define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
3431 #else
3432 #define has_unc(buf) 0
3433 #endif
3435 #ifdef DOSISH_DRIVE_LETTER
3436 static inline int
3437 has_drive_letter(const char *buf)
3439 if (ISALPHA(buf[0]) && buf[1] == ':') {
3440 return 1;
3442 else {
3443 return 0;
3447 #ifndef _WIN32
3448 static char*
3449 getcwdofdrv(int drv)
3451 char drive[4];
3452 char *drvcwd, *oldcwd;
3454 drive[0] = drv;
3455 drive[1] = ':';
3456 drive[2] = '\0';
3458 /* the only way that I know to get the current directory
3459 of a particular drive is to change chdir() to that drive,
3460 so save the old cwd before chdir()
3462 oldcwd = ruby_getcwd();
3463 if (chdir(drive) == 0) {
3464 drvcwd = ruby_getcwd();
3465 chdir(oldcwd);
3466 xfree(oldcwd);
3468 else {
3469 /* perhaps the drive is not exist. we return only drive letter */
3470 drvcwd = strdup(drive);
3472 return drvcwd;
3475 static inline int
3476 not_same_drive(VALUE path, int drive)
3478 const char *p = RSTRING_PTR(path);
3479 if (RSTRING_LEN(path) < 2) return 0;
3480 if (has_drive_letter(p)) {
3481 return TOLOWER(p[0]) != TOLOWER(drive);
3483 else {
3484 return has_unc(p);
3487 #endif /* _WIN32 */
3488 #endif /* DOSISH_DRIVE_LETTER */
3490 static inline char *
3491 skiproot(const char *path, const char *end, rb_encoding *enc)
3493 #ifdef DOSISH_DRIVE_LETTER
3494 if (path + 2 <= end && has_drive_letter(path)) path += 2;
3495 #endif
3496 while (path < end && isdirsep(*path)) path++;
3497 return (char *)path;
3500 #define nextdirsep rb_enc_path_next
3501 char *
3502 rb_enc_path_next(const char *s, const char *e, rb_encoding *enc)
3504 while (s < e && !isdirsep(*s)) {
3505 Inc(s, e, enc);
3507 return (char *)s;
3510 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3511 #define skipprefix rb_enc_path_skip_prefix
3512 #else
3513 #define skipprefix(path, end, enc) (path)
3514 #endif
3515 char *
3516 rb_enc_path_skip_prefix(const char *path, const char *end, rb_encoding *enc)
3518 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3519 #ifdef DOSISH_UNC
3520 if (path + 2 <= end && isdirsep(path[0]) && isdirsep(path[1])) {
3521 path += 2;
3522 while (path < end && isdirsep(*path)) path++;
3523 if ((path = rb_enc_path_next(path, end, enc)) < end && path[0] && path[1] && !isdirsep(path[1]))
3524 path = rb_enc_path_next(path + 1, end, enc);
3525 return (char *)path;
3527 #endif
3528 #ifdef DOSISH_DRIVE_LETTER
3529 if (has_drive_letter(path))
3530 return (char *)(path + 2);
3531 #endif
3532 #endif /* defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER) */
3533 return (char *)path;
3536 static inline char *
3537 skipprefixroot(const char *path, const char *end, rb_encoding *enc)
3539 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3540 char *p = skipprefix(path, end, enc);
3541 while (isdirsep(*p)) p++;
3542 return p;
3543 #else
3544 return skiproot(path, end, enc);
3545 #endif
3548 #define strrdirsep rb_enc_path_last_separator
3549 char *
3550 rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
3552 char *last = NULL;
3553 while (path < end) {
3554 if (isdirsep(*path)) {
3555 const char *tmp = path++;
3556 while (path < end && isdirsep(*path)) path++;
3557 if (path >= end) break;
3558 last = (char *)tmp;
3560 else {
3561 Inc(path, end, enc);
3564 return last;
3567 static char *
3568 chompdirsep(const char *path, const char *end, rb_encoding *enc)
3570 while (path < end) {
3571 if (isdirsep(*path)) {
3572 const char *last = path++;
3573 while (path < end && isdirsep(*path)) path++;
3574 if (path >= end) return (char *)last;
3576 else {
3577 Inc(path, end, enc);
3580 return (char *)path;
3583 char *
3584 rb_enc_path_end(const char *path, const char *end, rb_encoding *enc)
3586 if (path < end && isdirsep(*path)) path++;
3587 return chompdirsep(path, end, enc);
3590 static rb_encoding *
3591 fs_enc_check(VALUE path1, VALUE path2)
3593 rb_encoding *enc = rb_enc_check(path1, path2);
3594 int encidx = rb_enc_to_index(enc);
3595 if (encidx == ENCINDEX_US_ASCII) {
3596 encidx = rb_enc_get_index(path1);
3597 if (encidx == ENCINDEX_US_ASCII)
3598 encidx = rb_enc_get_index(path2);
3599 enc = rb_enc_from_index(encidx);
3601 return enc;
3604 #if USE_NTFS
3605 static char *
3606 ntfs_tail(const char *path, const char *end, rb_encoding *enc)
3608 while (path < end && *path == '.') path++;
3609 while (path < end && !isADS(*path)) {
3610 if (istrailinggarbage(*path)) {
3611 const char *last = path++;
3612 while (path < end && istrailinggarbage(*path)) path++;
3613 if (path >= end || isADS(*path)) return (char *)last;
3615 else if (isdirsep(*path)) {
3616 const char *last = path++;
3617 while (path < end && isdirsep(*path)) path++;
3618 if (path >= end) return (char *)last;
3619 if (isADS(*path)) path++;
3621 else {
3622 Inc(path, end, enc);
3625 return (char *)path;
3627 #endif /* USE_NTFS */
3629 #define BUFCHECK(cond) do {\
3630 bdiff = p - buf;\
3631 if (cond) {\
3632 do {buflen *= 2;} while (cond);\
3633 rb_str_resize(result, buflen);\
3634 buf = RSTRING_PTR(result);\
3635 p = buf + bdiff;\
3636 pend = buf + buflen;\
3638 } while (0)
3640 #define BUFINIT() (\
3641 p = buf = RSTRING_PTR(result),\
3642 buflen = RSTRING_LEN(result),\
3643 pend = p + buflen)
3645 #ifdef __APPLE__
3646 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3647 #else
3648 # define SKIPPATHSEP(p) 1
3649 #endif
3651 #define BUFCOPY(srcptr, srclen) do { \
3652 const int skip = SKIPPATHSEP(p); \
3653 rb_str_set_len(result, p-buf+skip); \
3654 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
3655 p += skip; \
3656 memcpy(p, (srcptr), (srclen)); \
3657 p += (srclen); \
3658 } while (0)
3660 #define WITH_ROOTDIFF(stmt) do { \
3661 long rootdiff = root - buf; \
3662 stmt; \
3663 root = buf + rootdiff; \
3664 } while (0)
3666 static VALUE
3667 copy_home_path(VALUE result, const char *dir)
3669 char *buf;
3670 #if defined DOSISH || defined __CYGWIN__
3671 char *p, *bend;
3672 rb_encoding *enc;
3673 #endif
3674 long dirlen;
3675 int encidx;
3677 dirlen = strlen(dir);
3678 rb_str_resize(result, dirlen);
3679 memcpy(buf = RSTRING_PTR(result), dir, dirlen);
3680 encidx = rb_filesystem_encindex();
3681 rb_enc_associate_index(result, encidx);
3682 #if defined DOSISH || defined __CYGWIN__
3683 enc = rb_enc_from_index(encidx);
3684 for (bend = (p = buf) + dirlen; p < bend; Inc(p, bend, enc)) {
3685 if (*p == '\\') {
3686 *p = '/';
3689 #endif
3690 return result;
3693 VALUE
3694 rb_home_dir_of(VALUE user, VALUE result)
3696 #ifdef HAVE_PWD_H
3697 struct passwd *pwPtr;
3698 #else
3699 extern char *getlogin(void);
3700 const char *pwPtr = 0;
3701 # define endpwent() ((void)0)
3702 #endif
3703 const char *dir, *username = RSTRING_PTR(user);
3704 rb_encoding *enc = rb_enc_get(user);
3705 #if defined _WIN32
3706 rb_encoding *fsenc = rb_utf8_encoding();
3707 #else
3708 rb_encoding *fsenc = rb_filesystem_encoding();
3709 #endif
3710 if (enc != fsenc) {
3711 dir = username = RSTRING_PTR(rb_str_conv_enc(user, enc, fsenc));
3714 #ifdef HAVE_PWD_H
3715 pwPtr = getpwnam(username);
3716 #else
3717 if (strcasecmp(username, getlogin()) == 0)
3718 dir = pwPtr = getenv("HOME");
3719 #endif
3720 if (!pwPtr) {
3721 endpwent();
3722 rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user);
3724 #ifdef HAVE_PWD_H
3725 dir = pwPtr->pw_dir;
3726 #endif
3727 copy_home_path(result, dir);
3728 endpwent();
3729 return result;
3732 #ifndef _WIN32 /* this encompasses rb_file_expand_path_internal */
3733 VALUE
3734 rb_default_home_dir(VALUE result)
3736 const char *dir = getenv("HOME");
3738 #if defined HAVE_PWD_H
3739 if (!dir) {
3740 /* We'll look up the user's default home dir in the password db by
3741 * login name, if possible, and failing that will fall back to looking
3742 * the information up by uid (as would be needed for processes that
3743 * are not a descendant of login(1) or a work-alike).
3745 * While the lookup by uid is more likely to succeed (since we always
3746 * have a uid, but may or may not have a login name), we prefer first
3747 * looking up by name to accommodate the possibility of multiple login
3748 * names (each with its own record in the password database, so each
3749 * with a potentially different home directory) being mapped to the
3750 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
3752 VALUE login_name = rb_getlogin();
3754 # if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
3755 /* This is a corner case, but for backward compatibility reasons we
3756 * want to emit this error if neither the lookup by login name nor
3757 * lookup by getuid() has a chance of succeeding.
3759 if (NIL_P(login_name)) {
3760 rb_raise(rb_eArgError, "couldn't find login name -- expanding '~'");
3762 # endif /* !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID) */
3764 VALUE pw_dir = rb_getpwdirnam_for_login(login_name);
3765 if (NIL_P(pw_dir)) {
3766 pw_dir = rb_getpwdiruid();
3767 if (NIL_P(pw_dir)) {
3768 rb_raise(rb_eArgError, "couldn't find home for uid '%ld'", (long)getuid());
3772 /* found it */
3773 copy_home_path(result, RSTRING_PTR(pw_dir));
3774 rb_str_resize(pw_dir, 0);
3775 return result;
3777 #endif /* defined HAVE_PWD_H */
3778 if (!dir) {
3779 rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding '~'");
3781 return copy_home_path(result, dir);
3784 static VALUE
3785 ospath_new(const char *ptr, long len, rb_encoding *fsenc)
3787 #if NORMALIZE_UTF8PATH
3788 VALUE path = rb_str_normalize_ospath(ptr, len);
3789 rb_enc_associate(path, fsenc);
3790 return path;
3791 #else
3792 return rb_enc_str_new(ptr, len, fsenc);
3793 #endif
3796 static char *
3797 append_fspath(VALUE result, VALUE fname, char *dir, rb_encoding **enc, rb_encoding *fsenc)
3799 char *buf, *cwdp = dir;
3800 VALUE dirname = Qnil;
3801 size_t dirlen = strlen(dir), buflen = rb_str_capacity(result);
3803 if (NORMALIZE_UTF8PATH || *enc != fsenc) {
3804 dirname = ospath_new(dir, dirlen, fsenc);
3805 if (!rb_enc_compatible(fname, dirname)) {
3806 xfree(dir);
3807 /* rb_enc_check must raise because the two encodings are not
3808 * compatible. */
3809 rb_enc_check(fname, dirname);
3810 rb_bug("unreachable");
3812 rb_encoding *direnc = fs_enc_check(fname, dirname);
3813 if (direnc != fsenc) {
3814 dirname = rb_str_conv_enc(dirname, fsenc, direnc);
3815 RSTRING_GETMEM(dirname, cwdp, dirlen);
3817 else if (NORMALIZE_UTF8PATH) {
3818 RSTRING_GETMEM(dirname, cwdp, dirlen);
3820 *enc = direnc;
3822 do {buflen *= 2;} while (dirlen > buflen);
3823 rb_str_resize(result, buflen);
3824 buf = RSTRING_PTR(result);
3825 memcpy(buf, cwdp, dirlen);
3826 xfree(dir);
3827 if (!NIL_P(dirname)) rb_str_resize(dirname, 0);
3828 rb_enc_associate(result, *enc);
3829 return buf + dirlen;
3832 VALUE
3833 rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_name, VALUE result)
3835 const char *s, *b, *fend;
3836 char *buf, *p, *pend, *root;
3837 size_t buflen, bdiff;
3838 rb_encoding *enc, *fsenc = rb_filesystem_encoding();
3840 s = StringValuePtr(fname);
3841 fend = s + RSTRING_LEN(fname);
3842 enc = rb_enc_get(fname);
3843 BUFINIT();
3845 if (s[0] == '~' && abs_mode == 0) { /* execute only if NOT absolute_path() */
3846 long userlen = 0;
3847 if (isdirsep(s[1]) || s[1] == '\0') {
3848 buf = 0;
3849 b = 0;
3850 rb_str_set_len(result, 0);
3851 if (*++s) ++s;
3852 rb_default_home_dir(result);
3854 else {
3855 s = nextdirsep(b = s, fend, enc);
3856 b++; /* b[0] is '~' */
3857 userlen = s - b;
3858 BUFCHECK(bdiff + userlen >= buflen);
3859 memcpy(p, b, userlen);
3860 ENC_CODERANGE_CLEAR(result);
3861 rb_str_set_len(result, userlen);
3862 rb_enc_associate(result, enc);
3863 rb_home_dir_of(result, result);
3864 buf = p + 1;
3865 p += userlen;
3867 if (!rb_is_absolute_path(RSTRING_PTR(result))) {
3868 if (userlen) {
3869 rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE,
3870 (int)userlen, b, fname);
3872 else {
3873 rb_raise(rb_eArgError, "non-absolute home");
3876 BUFINIT();
3877 p = pend;
3879 #ifdef DOSISH_DRIVE_LETTER
3880 /* skip drive letter */
3881 else if (has_drive_letter(s)) {
3882 if (isdirsep(s[2])) {
3883 /* specified drive letter, and full path */
3884 /* skip drive letter */
3885 BUFCHECK(bdiff + 2 >= buflen);
3886 memcpy(p, s, 2);
3887 p += 2;
3888 s += 2;
3889 rb_enc_copy(result, fname);
3891 else {
3892 /* specified drive, but not full path */
3893 int same = 0;
3894 if (!NIL_P(dname) && !not_same_drive(dname, s[0])) {
3895 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3896 BUFINIT();
3897 if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) {
3898 /* ok, same drive */
3899 same = 1;
3902 if (!same) {
3903 char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc);
3904 BUFINIT();
3905 p = e;
3907 else {
3908 rb_enc_associate(result, enc = fs_enc_check(result, fname));
3909 p = pend;
3911 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3912 s += 2;
3915 #endif /* DOSISH_DRIVE_LETTER */
3916 else if (!rb_is_absolute_path(s)) {
3917 if (!NIL_P(dname)) {
3918 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3919 rb_enc_associate(result, fs_enc_check(result, fname));
3920 BUFINIT();
3921 p = pend;
3923 else {
3924 char *e = append_fspath(result, fname, ruby_getcwd(), &enc, fsenc);
3925 BUFINIT();
3926 p = e;
3928 #if defined DOSISH || defined __CYGWIN__
3929 if (isdirsep(*s)) {
3930 /* specified full path, but not drive letter nor UNC */
3931 /* we need to get the drive letter or UNC share name */
3932 p = skipprefix(buf, p, enc);
3934 else
3935 #endif /* defined DOSISH || defined __CYGWIN__ */
3936 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3938 else {
3939 size_t len;
3940 b = s;
3941 do s++; while (isdirsep(*s));
3942 len = s - b;
3943 p = buf + len;
3944 BUFCHECK(bdiff >= buflen);
3945 memset(buf, '/', len);
3946 rb_str_set_len(result, len);
3947 rb_enc_associate(result, fs_enc_check(result, fname));
3949 if (p > buf && p[-1] == '/')
3950 --p;
3951 else {
3952 rb_str_set_len(result, p-buf);
3953 BUFCHECK(bdiff + 1 >= buflen);
3954 *p = '/';
3957 rb_str_set_len(result, p-buf+1);
3958 BUFCHECK(bdiff + 1 >= buflen);
3959 p[1] = 0;
3960 root = skipprefix(buf, p+1, enc);
3962 b = s;
3963 while (*s) {
3964 switch (*s) {
3965 case '.':
3966 if (b == s++) { /* beginning of path element */
3967 switch (*s) {
3968 case '\0':
3969 b = s;
3970 break;
3971 case '.':
3972 if (*(s+1) == '\0' || isdirsep(*(s+1))) {
3973 /* We must go back to the parent */
3974 char *n;
3975 *p = '\0';
3976 if (!(n = strrdirsep(root, p, enc))) {
3977 *p = '/';
3979 else {
3980 p = n;
3982 b = ++s;
3984 #if USE_NTFS
3985 else {
3986 do ++s; while (istrailinggarbage(*s));
3988 #endif /* USE_NTFS */
3989 break;
3990 case '/':
3991 #if defined DOSISH || defined __CYGWIN__
3992 case '\\':
3993 #endif
3994 b = ++s;
3995 break;
3996 default:
3997 /* ordinary path element, beginning don't move */
3998 break;
4001 #if USE_NTFS
4002 else {
4003 --s;
4004 case ' ': {
4005 const char *e = s;
4006 while (s < fend && istrailinggarbage(*s)) s++;
4007 if (s >= fend) {
4008 s = e;
4009 goto endpath;
4013 #endif /* USE_NTFS */
4014 break;
4015 case '/':
4016 #if defined DOSISH || defined __CYGWIN__
4017 case '\\':
4018 #endif
4019 if (s > b) {
4020 WITH_ROOTDIFF(BUFCOPY(b, s-b));
4021 *p = '/';
4023 b = ++s;
4024 break;
4025 default:
4026 #ifdef __APPLE__
4028 int n = ignored_char_p(s, fend, enc);
4029 if (n) {
4030 if (s > b) {
4031 WITH_ROOTDIFF(BUFCOPY(b, s-b));
4032 *p = '\0';
4034 b = s += n;
4035 break;
4038 #endif /* __APPLE__ */
4039 Inc(s, fend, enc);
4040 break;
4044 if (s > b) {
4045 #if USE_NTFS
4046 # if USE_NTFS_ADS
4047 static const char prime[] = ":$DATA";
4048 enum {prime_len = sizeof(prime) -1};
4049 # endif
4050 endpath:
4051 # if USE_NTFS_ADS
4052 if (s > b + prime_len && strncasecmp(s - prime_len, prime, prime_len) == 0) {
4053 /* alias of stream */
4054 /* get rid of a bug of x64 VC++ */
4055 if (isADS(*(s - (prime_len+1)))) {
4056 s -= prime_len + 1; /* prime */
4058 else if (memchr(b, ':', s - prime_len - b)) {
4059 s -= prime_len; /* alternative */
4062 # endif /* USE_NTFS_ADS */
4063 #endif /* USE_NTFS */
4064 BUFCOPY(b, s-b);
4065 rb_str_set_len(result, p-buf);
4067 if (p == skiproot(buf, p + !!*p, enc) - 1) p++;
4069 #if USE_NTFS
4070 *p = '\0';
4071 if ((s = strrdirsep(b = buf, p, enc)) != 0 && !strpbrk(s, "*?")) {
4072 VALUE tmp, v;
4073 size_t len;
4074 int encidx;
4075 WCHAR *wstr;
4076 WIN32_FIND_DATAW wfd;
4077 HANDLE h;
4078 #ifdef __CYGWIN__
4079 #ifdef HAVE_CYGWIN_CONV_PATH
4080 char *w32buf = NULL;
4081 const int flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE;
4082 #else
4083 char w32buf[MAXPATHLEN];
4084 #endif /* HAVE_CYGWIN_CONV_PATH */
4085 const char *path;
4086 ssize_t bufsize;
4087 int lnk_added = 0, is_symlink = 0;
4088 struct stat st;
4089 p = (char *)s;
4090 len = strlen(p);
4091 if (lstat_without_gvl(buf, &st) == 0 && S_ISLNK(st.st_mode)) {
4092 is_symlink = 1;
4093 if (len > 4 && STRCASECMP(p + len - 4, ".lnk") != 0) {
4094 lnk_added = 1;
4097 path = *buf ? buf : "/";
4098 #ifdef HAVE_CYGWIN_CONV_PATH
4099 bufsize = cygwin_conv_path(flags, path, NULL, 0);
4100 if (bufsize > 0) {
4101 bufsize += len;
4102 if (lnk_added) bufsize += 4;
4103 w32buf = ALLOCA_N(char, bufsize);
4104 if (cygwin_conv_path(flags, path, w32buf, bufsize) == 0) {
4105 b = w32buf;
4108 #else /* !HAVE_CYGWIN_CONV_PATH */
4109 bufsize = MAXPATHLEN;
4110 if (cygwin_conv_to_win32_path(path, w32buf) == 0) {
4111 b = w32buf;
4113 #endif /* !HAVE_CYGWIN_CONV_PATH */
4114 if (is_symlink && b == w32buf) {
4115 *p = '\\';
4116 strlcat(w32buf, p, bufsize);
4117 if (lnk_added) {
4118 strlcat(w32buf, ".lnk", bufsize);
4121 else {
4122 lnk_added = 0;
4124 *p = '/';
4125 #endif /* __CYGWIN__ */
4126 rb_str_set_len(result, p - buf + strlen(p));
4127 encidx = ENCODING_GET(result);
4128 tmp = result;
4129 if (encidx != ENCINDEX_UTF_8 && !is_ascii_string(result)) {
4130 tmp = rb_str_encode_ospath(result);
4132 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
4133 wstr = ALLOCV_N(WCHAR, v, len);
4134 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, wstr, len);
4135 if (tmp != result) rb_str_set_len(tmp, 0);
4136 h = FindFirstFileW(wstr, &wfd);
4137 ALLOCV_END(v);
4138 if (h != INVALID_HANDLE_VALUE) {
4139 size_t wlen;
4140 FindClose(h);
4141 len = lstrlenW(wfd.cFileName);
4142 #ifdef __CYGWIN__
4143 if (lnk_added && len > 4 &&
4144 wcscasecmp(wfd.cFileName + len - 4, L".lnk") == 0) {
4145 wfd.cFileName[len -= 4] = L'\0';
4147 #else
4148 p = (char *)s;
4149 #endif
4150 ++p;
4151 wlen = (int)len;
4152 len = WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, NULL, 0, NULL, NULL);
4153 if (tmp == result) {
4154 BUFCHECK(bdiff + len >= buflen);
4155 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, p, len + 1, NULL, NULL);
4157 else {
4158 rb_str_modify_expand(tmp, len);
4159 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, RSTRING_PTR(tmp), len + 1, NULL, NULL);
4160 rb_str_cat_conv_enc_opts(result, bdiff, RSTRING_PTR(tmp), len,
4161 rb_utf8_encoding(), 0, Qnil);
4162 BUFINIT();
4163 rb_str_resize(tmp, 0);
4165 p += len;
4167 #ifdef __CYGWIN__
4168 else {
4169 p += strlen(p);
4171 #endif
4173 #endif /* USE_NTFS */
4175 rb_str_set_len(result, p - buf);
4176 rb_enc_check(fname, result);
4177 ENC_CODERANGE_CLEAR(result);
4178 return result;
4180 #endif /* !_WIN32 (this ifdef started above rb_default_home_dir) */
4182 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, 1)
4184 static VALUE
4185 str_shrink(VALUE str)
4187 rb_str_resize(str, RSTRING_LEN(str));
4188 return str;
4191 #define expand_path(fname, dname, abs_mode, long_name, result) \
4192 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
4194 #define check_expand_path_args(fname, dname) \
4195 (((fname) = rb_get_path(fname)), \
4196 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
4198 static VALUE
4199 file_expand_path_1(VALUE fname)
4201 return rb_file_expand_path_internal(fname, Qnil, 0, 0, EXPAND_PATH_BUFFER());
4204 VALUE
4205 rb_file_expand_path(VALUE fname, VALUE dname)
4207 check_expand_path_args(fname, dname);
4208 return expand_path(fname, dname, 0, 1, EXPAND_PATH_BUFFER());
4211 VALUE
4212 rb_file_expand_path_fast(VALUE fname, VALUE dname)
4214 return expand_path(fname, dname, 0, 0, EXPAND_PATH_BUFFER());
4217 VALUE
4218 rb_file_s_expand_path(int argc, const VALUE *argv)
4220 rb_check_arity(argc, 1, 2);
4221 return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil);
4225 * call-seq:
4226 * File.expand_path(file_name [, dir_string] ) -> abs_file_name
4228 * Converts a pathname to an absolute pathname. Relative paths are
4229 * referenced from the current working directory of the process unless
4230 * +dir_string+ is given, in which case it will be used as the
4231 * starting point. The given pathname may start with a
4232 * ``<code>~</code>'', which expands to the process owner's home
4233 * directory (the environment variable +HOME+ must be set
4234 * correctly). ``<code>~</code><i>user</i>'' expands to the named
4235 * user's home directory.
4237 * File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
4239 * A simple example of using +dir_string+ is as follows.
4240 * File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
4242 * A more complex example which also resolves parent directory is as follows.
4243 * Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
4245 * File.expand_path("../../lib/mygem.rb", __FILE__)
4246 * #=> ".../path/to/project/lib/mygem.rb"
4248 * So first it resolves the parent of __FILE__, that is bin/, then go to the
4249 * parent, the root of the project and appends +lib/mygem.rb+.
4252 static VALUE
4253 s_expand_path(int c, const VALUE * v, VALUE _)
4255 return rb_file_s_expand_path(c, v);
4258 VALUE
4259 rb_file_absolute_path(VALUE fname, VALUE dname)
4261 check_expand_path_args(fname, dname);
4262 return expand_path(fname, dname, 1, 1, EXPAND_PATH_BUFFER());
4265 VALUE
4266 rb_file_s_absolute_path(int argc, const VALUE *argv)
4268 rb_check_arity(argc, 1, 2);
4269 return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil);
4273 * call-seq:
4274 * File.absolute_path(file_name [, dir_string] ) -> abs_file_name
4276 * Converts a pathname to an absolute pathname. Relative paths are
4277 * referenced from the current working directory of the process unless
4278 * <i>dir_string</i> is given, in which case it will be used as the
4279 * starting point. If the given pathname starts with a ``<code>~</code>''
4280 * it is NOT expanded, it is treated as a normal directory name.
4282 * File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4285 static VALUE
4286 s_absolute_path(int c, const VALUE * v, VALUE _)
4288 return rb_file_s_absolute_path(c, v);
4292 * call-seq:
4293 * File.absolute_path?(file_name) -> true or false
4295 * Returns <code>true</code> if +file_name+ is an absolute path, and
4296 * <code>false</code> otherwise.
4298 * File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4301 static VALUE
4302 s_absolute_path_p(VALUE klass, VALUE fname)
4304 VALUE path = rb_get_path(fname);
4306 if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse;
4307 return Qtrue;
4310 enum rb_realpath_mode {
4311 RB_REALPATH_CHECK,
4312 RB_REALPATH_DIR,
4313 RB_REALPATH_STRICT,
4314 RB_REALPATH_MODE_MAX
4317 static int
4318 realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE fallback,
4319 VALUE loopcheck, enum rb_realpath_mode mode, int last)
4321 const char *pend = unresolved + strlen(unresolved);
4322 rb_encoding *enc = rb_enc_get(*resolvedp);
4323 ID resolving;
4324 CONST_ID(resolving, "resolving");
4325 while (unresolved < pend) {
4326 const char *testname = unresolved;
4327 const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc);
4328 long testnamelen = unresolved_firstsep - unresolved;
4329 const char *unresolved_nextname = unresolved_firstsep;
4330 while (unresolved_nextname < pend && isdirsep(*unresolved_nextname))
4331 unresolved_nextname++;
4332 unresolved = unresolved_nextname;
4333 if (testnamelen == 1 && testname[0] == '.') {
4335 else if (testnamelen == 2 && testname[0] == '.' && testname[1] == '.') {
4336 if (*prefixlenp < RSTRING_LEN(*resolvedp)) {
4337 const char *resolved_str = RSTRING_PTR(*resolvedp);
4338 const char *resolved_names = resolved_str + *prefixlenp;
4339 const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), enc);
4340 long len = lastsep ? lastsep - resolved_names : 0;
4341 rb_str_resize(*resolvedp, *prefixlenp + len);
4344 else {
4345 VALUE checkval;
4346 VALUE testpath = rb_str_dup(*resolvedp);
4347 if (*prefixlenp < RSTRING_LEN(testpath))
4348 rb_str_cat2(testpath, "/");
4349 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4350 if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) {
4351 const char *prefix = RSTRING_PTR(testpath);
4352 const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc);
4353 if (!isdirsep(*last)) rb_str_cat2(testpath, "/");
4355 #endif
4356 rb_str_cat(testpath, testname, testnamelen);
4357 checkval = rb_hash_aref(loopcheck, testpath);
4358 if (!NIL_P(checkval)) {
4359 if (checkval == ID2SYM(resolving)) {
4360 if (mode == RB_REALPATH_CHECK) {
4361 errno = ELOOP;
4362 return -1;
4364 rb_syserr_fail_path(ELOOP, testpath);
4366 else {
4367 *resolvedp = rb_str_dup(checkval);
4370 else {
4371 struct stat sbuf;
4372 int ret;
4373 ret = lstat_without_gvl(RSTRING_PTR(testpath), &sbuf);
4374 if (ret == -1) {
4375 int e = errno;
4376 if (e == ENOENT && !NIL_P(fallback)) {
4377 if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) {
4378 rb_str_replace(*resolvedp, fallback);
4379 return 0;
4382 if (mode == RB_REALPATH_CHECK) return -1;
4383 if (e == ENOENT) {
4384 if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep)
4385 rb_syserr_fail_path(e, testpath);
4386 *resolvedp = testpath;
4387 break;
4389 else {
4390 rb_syserr_fail_path(e, testpath);
4393 #ifdef HAVE_READLINK
4394 if (S_ISLNK(sbuf.st_mode)) {
4395 VALUE link;
4396 VALUE link_orig = Qnil;
4397 const char *link_prefix, *link_names;
4398 long link_prefixlen;
4399 rb_hash_aset(loopcheck, testpath, ID2SYM(resolving));
4400 link = rb_readlink(testpath, enc);
4401 link_prefix = RSTRING_PTR(link);
4402 link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link));
4403 link_prefixlen = link_names - link_prefix;
4404 if (link_prefixlen > 0) {
4405 rb_encoding *tmpenc, *linkenc = rb_enc_get(link);
4406 link_orig = link;
4407 link = rb_str_subseq(link, 0, link_prefixlen);
4408 tmpenc = fs_enc_check(*resolvedp, link);
4409 if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc);
4410 *resolvedp = link;
4411 *prefixlenp = link_prefixlen;
4413 if (realpath_rec(prefixlenp, resolvedp, link_names, testpath,
4414 loopcheck, mode, !*unresolved_firstsep))
4415 return -1;
4416 RB_GC_GUARD(link_orig);
4417 rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp));
4419 else
4420 #endif /* HAVE_READLINK */
4422 VALUE s = rb_str_dup_frozen(testpath);
4423 rb_hash_aset(loopcheck, s, s);
4424 *resolvedp = testpath;
4429 return 0;
4432 static VALUE
4433 rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4435 long prefixlen;
4436 VALUE resolved;
4437 VALUE unresolved_path;
4438 VALUE loopcheck;
4439 VALUE curdir = Qnil;
4441 rb_encoding *enc;
4442 char *path_names = NULL, *basedir_names = NULL, *curdir_names = NULL;
4443 char *ptr, *prefixptr = NULL, *pend;
4444 long len;
4446 unresolved_path = rb_str_dup_frozen(path);
4448 if (!NIL_P(basedir)) {
4449 FilePathValue(basedir);
4450 basedir = TO_OSPATH(rb_str_dup_frozen(basedir));
4453 enc = rb_enc_get(unresolved_path);
4454 unresolved_path = TO_OSPATH(unresolved_path);
4455 RSTRING_GETMEM(unresolved_path, ptr, len);
4456 path_names = skipprefixroot(ptr, ptr + len, rb_enc_get(unresolved_path));
4457 if (ptr != path_names) {
4458 resolved = rb_str_subseq(unresolved_path, 0, path_names - ptr);
4459 goto root_found;
4462 if (!NIL_P(basedir)) {
4463 RSTRING_GETMEM(basedir, ptr, len);
4464 basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir));
4465 if (ptr != basedir_names) {
4466 resolved = rb_str_subseq(basedir, 0, basedir_names - ptr);
4467 goto root_found;
4471 curdir = rb_dir_getwd_ospath();
4472 RSTRING_GETMEM(curdir, ptr, len);
4473 curdir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(curdir));
4474 resolved = rb_str_subseq(curdir, 0, curdir_names - ptr);
4476 root_found:
4477 RSTRING_GETMEM(resolved, prefixptr, prefixlen);
4478 pend = prefixptr + prefixlen;
4479 ptr = chompdirsep(prefixptr, pend, enc);
4480 if (ptr < pend) {
4481 prefixlen = ++ptr - prefixptr;
4482 rb_str_set_len(resolved, prefixlen);
4484 #ifdef FILE_ALT_SEPARATOR
4485 while (prefixptr < ptr) {
4486 if (*prefixptr == FILE_ALT_SEPARATOR) {
4487 *prefixptr = '/';
4489 Inc(prefixptr, pend, enc);
4491 #endif
4493 switch (rb_enc_to_index(enc)) {
4494 case ENCINDEX_ASCII_8BIT:
4495 case ENCINDEX_US_ASCII:
4496 rb_enc_associate_index(resolved, rb_filesystem_encindex());
4499 loopcheck = rb_hash_new();
4500 if (curdir_names) {
4501 if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0))
4502 return Qnil;
4504 if (basedir_names) {
4505 if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0))
4506 return Qnil;
4508 if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1))
4509 return Qnil;
4511 if (origenc && origenc != rb_enc_get(resolved)) {
4512 if (rb_enc_str_asciionly_p(resolved)) {
4513 rb_enc_associate(resolved, origenc);
4515 else {
4516 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4520 RB_GC_GUARD(unresolved_path);
4521 RB_GC_GUARD(curdir);
4522 return resolved;
4525 static VALUE rb_file_join(VALUE ary);
4527 #ifndef HAVE_REALPATH
4528 static VALUE
4529 rb_check_realpath_emulate_try(VALUE arg)
4531 VALUE *args = (VALUE *)arg;
4532 return rb_check_realpath_emulate(args[0], args[1], (rb_encoding *)args[2], RB_REALPATH_CHECK);
4535 static VALUE
4536 rb_check_realpath_emulate_rescue(VALUE arg, VALUE exc)
4538 return Qnil;
4540 #endif /* HAVE_REALPATH */
4542 static VALUE
4543 rb_check_realpath_internal(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4545 #ifdef HAVE_REALPATH
4546 VALUE unresolved_path;
4547 char *resolved_ptr = NULL;
4548 VALUE resolved;
4550 if (mode == RB_REALPATH_DIR) {
4551 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4554 unresolved_path = rb_str_dup_frozen(path);
4555 if (*RSTRING_PTR(unresolved_path) != '/' && !NIL_P(basedir)) {
4556 unresolved_path = rb_file_join(rb_assoc_new(basedir, unresolved_path));
4558 if (origenc) unresolved_path = TO_OSPATH(unresolved_path);
4560 if ((resolved_ptr = realpath(RSTRING_PTR(unresolved_path), NULL)) == NULL) {
4561 /* glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4562 returning ENOTDIR in that case.
4563 glibc realpath(3) can also return ENOENT for paths that exist,
4564 such as /dev/fd/5.
4565 Fallback to the emulated approach in either of those cases. */
4566 if (errno == ENOTDIR ||
4567 (errno == ENOENT && rb_file_exist_p(0, unresolved_path))) {
4568 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4571 if (mode == RB_REALPATH_CHECK) {
4572 return Qnil;
4574 rb_sys_fail_path(unresolved_path);
4576 resolved = ospath_new(resolved_ptr, strlen(resolved_ptr), rb_filesystem_encoding());
4577 free(resolved_ptr);
4579 # if !defined(__LINUX__) && !defined(__APPLE__)
4580 /* As `resolved` is a String in the filesystem encoding, no
4581 * conversion is needed */
4582 struct stat st;
4583 if (stat_without_gvl(RSTRING_PTR(resolved), &st) < 0) {
4584 if (mode == RB_REALPATH_CHECK) {
4585 return Qnil;
4587 rb_sys_fail_path(unresolved_path);
4589 # endif /* !defined(__LINUX__) && !defined(__APPLE__) */
4591 if (origenc && origenc != rb_enc_get(resolved)) {
4592 if (!rb_enc_str_asciionly_p(resolved)) {
4593 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4595 rb_enc_associate(resolved, origenc);
4598 if (is_broken_string(resolved)) {
4599 rb_enc_associate(resolved, rb_filesystem_encoding());
4600 if (is_broken_string(resolved)) {
4601 rb_enc_associate(resolved, rb_ascii8bit_encoding());
4605 RB_GC_GUARD(unresolved_path);
4606 return resolved;
4607 #else /* !HAVE_REALPATH */
4608 if (mode == RB_REALPATH_CHECK) {
4609 VALUE arg[3];
4610 arg[0] = basedir;
4611 arg[1] = path;
4612 arg[2] = (VALUE)origenc;
4614 return rb_rescue(rb_check_realpath_emulate_try, (VALUE)arg,
4615 rb_check_realpath_emulate_rescue, Qnil);
4617 else {
4618 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4620 #endif /* HAVE_REALPATH */
4623 VALUE
4624 rb_realpath_internal(VALUE basedir, VALUE path, int strict)
4626 const enum rb_realpath_mode mode =
4627 strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR;
4628 return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode);
4631 VALUE
4632 rb_check_realpath(VALUE basedir, VALUE path, rb_encoding *enc)
4634 return rb_check_realpath_internal(basedir, path, enc, RB_REALPATH_CHECK);
4638 * call-seq:
4639 * File.realpath(pathname [, dir_string]) -> real_pathname
4641 * Returns the real (absolute) pathname of _pathname_ in the actual
4642 * filesystem not containing symlinks or useless dots.
4644 * If _dir_string_ is given, it is used as a base directory
4645 * for interpreting relative pathname instead of the current directory.
4647 * All components of the pathname must exist when this method is
4648 * called.
4650 static VALUE
4651 rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
4653 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4654 VALUE path = argv[0];
4655 FilePathValue(path);
4656 return rb_realpath_internal(basedir, path, 1);
4660 * call-seq:
4661 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4663 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4664 * The real pathname doesn't contain symlinks or useless dots.
4666 * If _dir_string_ is given, it is used as a base directory
4667 * for interpreting relative pathname instead of the current directory.
4669 * The last component of the real pathname can be nonexistent.
4671 static VALUE
4672 rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
4674 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4675 VALUE path = argv[0];
4676 FilePathValue(path);
4677 return rb_realpath_internal(basedir, path, 0);
4680 static size_t
4681 rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc)
4683 int len1, len2;
4684 unsigned int c;
4685 const char *s, *last;
4687 if (!e || !l2) return 0;
4689 c = rb_enc_codepoint_len(e, e + l2, &len1, enc);
4690 if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) {
4691 if (c == '.') return l0;
4692 s = p;
4693 e = p + l1;
4694 last = e;
4695 while (s < e) {
4696 if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s;
4697 s += len1;
4699 return last - p;
4701 if (l1 < l2) return l1;
4703 s = p+l1-l2;
4704 if (!at_char_boundary(p, s, p+l1, enc)) return 0;
4705 #if CASEFOLD_FILESYSTEM
4706 #define fncomp strncasecmp
4707 #else
4708 #define fncomp strncmp
4709 #endif
4710 if (fncomp(s, e, l2) == 0) {
4711 return l1-l2;
4713 return 0;
4716 const char *
4717 ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encoding *enc)
4719 const char *p, *q, *e, *end;
4720 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4721 const char *root;
4722 #endif
4723 long f = 0, n = -1;
4725 end = name + (alllen ? (size_t)*alllen : strlen(name));
4726 name = skipprefix(name, end, enc);
4727 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4728 root = name;
4729 #endif
4730 while (isdirsep(*name))
4731 name++;
4732 if (!*name) {
4733 p = name - 1;
4734 f = 1;
4735 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4736 if (name != root) {
4737 /* has slashes */
4739 #ifdef DOSISH_DRIVE_LETTER
4740 else if (*p == ':') {
4741 p++;
4742 f = 0;
4744 #endif /* DOSISH_DRIVE_LETTER */
4745 #ifdef DOSISH_UNC
4746 else {
4747 p = "/";
4749 #endif /* DOSISH_UNC */
4750 #endif /* defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC */
4752 else {
4753 if (!(p = strrdirsep(name, end, enc))) {
4754 p = name;
4756 else {
4757 while (isdirsep(*p)) p++; /* skip last / */
4759 #if USE_NTFS
4760 n = ntfs_tail(p, end, enc) - p;
4761 #else
4762 n = chompdirsep(p, end, enc) - p;
4763 #endif
4764 for (q = p; q - p < n && *q == '.'; q++);
4765 for (e = 0; q - p < n; Inc(q, end, enc)) {
4766 if (*q == '.') e = q;
4768 if (e) f = e - p;
4769 else f = n;
4772 if (baselen)
4773 *baselen = f;
4774 if (alllen)
4775 *alllen = n;
4776 return p;
4780 * call-seq:
4781 * File.basename(file_name [, suffix] ) -> base_name
4783 * Returns the last component of the filename given in
4784 * <i>file_name</i> (after first stripping trailing separators),
4785 * which can be formed using both File::SEPARATOR and
4786 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4787 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4788 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4789 * any extension will be removed.
4791 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4792 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4793 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4796 static VALUE
4797 rb_file_s_basename(int argc, VALUE *argv, VALUE _)
4799 VALUE fname, fext, basename;
4800 const char *name, *p;
4801 long f, n;
4802 rb_encoding *enc;
4804 fext = Qnil;
4805 if (rb_check_arity(argc, 1, 2) == 2) {
4806 fext = argv[1];
4807 StringValue(fext);
4808 enc = check_path_encoding(fext);
4810 fname = argv[0];
4811 FilePathStringValue(fname);
4812 if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
4813 enc = rb_enc_get(fname);
4814 fext = Qnil;
4816 if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
4817 return rb_str_new_shared(fname);
4819 p = ruby_enc_find_basename(name, &f, &n, enc);
4820 if (n >= 0) {
4821 if (NIL_P(fext)) {
4822 f = n;
4824 else {
4825 const char *fp;
4826 fp = StringValueCStr(fext);
4827 if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
4828 f = n;
4830 RB_GC_GUARD(fext);
4832 if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
4835 basename = rb_str_new(p, f);
4836 rb_enc_copy(basename, fname);
4837 return basename;
4840 static VALUE rb_file_dirname_n(VALUE fname, int n);
4843 * call-seq:
4844 * File.dirname(file_name, level = 1) -> dir_name
4846 * Returns all components of the filename given in <i>file_name</i>
4847 * except the last one (after first stripping trailing separators).
4848 * The filename can be formed using both File::SEPARATOR and
4849 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4850 * not <code>nil</code>.
4852 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4854 * If +level+ is given, removes the last +level+ components, not only
4855 * one.
4857 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4858 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4861 static VALUE
4862 rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
4864 int n = 1;
4865 if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
4866 n = NUM2INT(argv[1]);
4868 return rb_file_dirname_n(argv[0], n);
4871 VALUE
4872 rb_file_dirname(VALUE fname)
4874 return rb_file_dirname_n(fname, 1);
4877 static VALUE
4878 rb_file_dirname_n(VALUE fname, int n)
4880 const char *name, *root, *p, *end;
4881 VALUE dirname;
4882 rb_encoding *enc;
4883 VALUE sepsv = 0;
4884 const char **seps;
4886 if (n < 0) rb_raise(rb_eArgError, "negative level: %d", n);
4887 FilePathStringValue(fname);
4888 name = StringValueCStr(fname);
4889 end = name + RSTRING_LEN(fname);
4890 enc = rb_enc_get(fname);
4891 root = skiproot(name, end, enc);
4892 #ifdef DOSISH_UNC
4893 if (root > name + 1 && isdirsep(*name))
4894 root = skipprefix(name = root - 2, end, enc);
4895 #else
4896 if (root > name + 1)
4897 name = root - 1;
4898 #endif
4899 if (n > (end - root + 1) / 2) {
4900 p = root;
4902 else {
4903 int i;
4904 switch (n) {
4905 case 0:
4906 p = end;
4907 break;
4908 case 1:
4909 if (!(p = strrdirsep(root, end, enc))) p = root;
4910 break;
4911 default:
4912 seps = ALLOCV_N(const char *, sepsv, n);
4913 for (i = 0; i < n; ++i) seps[i] = root;
4914 i = 0;
4915 for (p = root; p < end; ) {
4916 if (isdirsep(*p)) {
4917 const char *tmp = p++;
4918 while (p < end && isdirsep(*p)) p++;
4919 if (p >= end) break;
4920 seps[i++] = tmp;
4921 if (i == n) i = 0;
4923 else {
4924 Inc(p, end, enc);
4927 p = seps[i];
4928 ALLOCV_END(sepsv);
4929 break;
4932 if (p == name)
4933 return rb_usascii_str_new2(".");
4934 #ifdef DOSISH_DRIVE_LETTER
4935 if (has_drive_letter(name) && isdirsep(*(name + 2))) {
4936 const char *top = skiproot(name + 2, end, enc);
4937 dirname = rb_str_new(name, 3);
4938 rb_str_cat(dirname, top, p - top);
4940 else
4941 #endif
4942 dirname = rb_str_new(name, p - name);
4943 #ifdef DOSISH_DRIVE_LETTER
4944 if (has_drive_letter(name) && root == name + 2 && p - name == 2)
4945 rb_str_cat(dirname, ".", 1);
4946 #endif
4947 rb_enc_copy(dirname, fname);
4948 return dirname;
4952 * accept a String, and return the pointer of the extension.
4953 * if len is passed, set the length of extension to it.
4954 * returned pointer is in ``name'' or NULL.
4955 * returns *len
4956 * no dot NULL 0
4957 * dotfile top 0
4958 * end with dot dot 1
4959 * .ext dot len of .ext
4960 * .ext:stream dot len of .ext without :stream (NTFS only)
4963 const char *
4964 ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc)
4966 const char *p, *e, *end = name + (len ? *len : (long)strlen(name));
4968 p = strrdirsep(name, end, enc); /* get the last path component */
4969 if (!p)
4970 p = name;
4971 else
4972 do name = ++p; while (isdirsep(*p));
4974 e = 0;
4975 while (*p && *p == '.') p++;
4976 while (*p) {
4977 if (*p == '.' || istrailinggarbage(*p)) {
4978 #if USE_NTFS
4979 const char *last = p++, *dot = last;
4980 while (istrailinggarbage(*p)) {
4981 if (*p == '.') dot = p;
4982 p++;
4984 if (!*p || isADS(*p)) {
4985 p = last;
4986 break;
4988 if (*last == '.' || dot > last) e = dot;
4989 continue;
4990 #else
4991 e = p; /* get the last dot of the last component */
4992 #endif /* USE_NTFS */
4994 #if USE_NTFS
4995 else if (isADS(*p)) {
4996 break;
4998 #endif
4999 else if (isdirsep(*p))
5000 break;
5001 Inc(p, end, enc);
5004 if (len) {
5005 /* no dot, or the only dot is first or end? */
5006 if (!e || e == name)
5007 *len = 0;
5008 else if (e+1 == p)
5009 *len = 1;
5010 else
5011 *len = p - e;
5013 return e;
5017 * call-seq:
5018 * File.extname(path) -> string
5020 * Returns the extension (the portion of file name in +path+
5021 * starting from the last period).
5023 * If +path+ is a dotfile, or starts with a period, then the starting
5024 * dot is not dealt with the start of the extension.
5026 * An empty string will also be returned when the period is the last character
5027 * in +path+.
5029 * On Windows, trailing dots are truncated.
5031 * File.extname("test.rb") #=> ".rb"
5032 * File.extname("a/b/d/test.rb") #=> ".rb"
5033 * File.extname(".a/b/d/test.rb") #=> ".rb"
5034 * File.extname("foo.") #=> "" on Windows
5035 * File.extname("foo.") #=> "." on non-Windows
5036 * File.extname("test") #=> ""
5037 * File.extname(".profile") #=> ""
5038 * File.extname(".profile.sh") #=> ".sh"
5042 static VALUE
5043 rb_file_s_extname(VALUE klass, VALUE fname)
5045 const char *name, *e;
5046 long len;
5047 VALUE extname;
5049 FilePathStringValue(fname);
5050 name = StringValueCStr(fname);
5051 len = RSTRING_LEN(fname);
5052 e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
5053 if (len < 1)
5054 return rb_str_new(0, 0);
5055 extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
5056 return extname;
5060 * call-seq:
5061 * File.path(path) -> string
5063 * Returns the string representation of the path
5065 * File.path(File::NULL) #=> "/dev/null"
5066 * File.path(Pathname.new("/tmp")) #=> "/tmp"
5070 static VALUE
5071 rb_file_s_path(VALUE klass, VALUE fname)
5073 return rb_get_path(fname);
5077 * call-seq:
5078 * File.split(file_name) -> array
5080 * Splits the given string into a directory and a file component and
5081 * returns them in a two-element array. See also File::dirname and
5082 * File::basename.
5084 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
5087 static VALUE
5088 rb_file_s_split(VALUE klass, VALUE path)
5090 FilePathStringValue(path); /* get rid of converting twice */
5091 return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));
5094 static VALUE
5095 file_inspect_join(VALUE ary, VALUE arg, int recur)
5097 if (recur || ary == arg) rb_raise(rb_eArgError, "recursive array");
5098 return rb_file_join(arg);
5101 static VALUE
5102 rb_file_join(VALUE ary)
5104 long len, i;
5105 VALUE result, tmp;
5106 const char *name, *tail;
5107 int checked = TRUE;
5108 rb_encoding *enc;
5110 if (RARRAY_LEN(ary) == 0) return rb_str_new(0, 0);
5112 len = 1;
5113 for (i=0; i<RARRAY_LEN(ary); i++) {
5114 tmp = RARRAY_AREF(ary, i);
5115 if (RB_TYPE_P(tmp, T_STRING)) {
5116 check_path_encoding(tmp);
5117 len += RSTRING_LEN(tmp);
5119 else {
5120 len += 10;
5123 len += RARRAY_LEN(ary) - 1;
5124 result = rb_str_buf_new(len);
5125 RBASIC_CLEAR_CLASS(result);
5126 for (i=0; i<RARRAY_LEN(ary); i++) {
5127 tmp = RARRAY_AREF(ary, i);
5128 switch (OBJ_BUILTIN_TYPE(tmp)) {
5129 case T_STRING:
5130 if (!checked) check_path_encoding(tmp);
5131 StringValueCStr(tmp);
5132 break;
5133 case T_ARRAY:
5134 if (ary == tmp) {
5135 rb_raise(rb_eArgError, "recursive array");
5137 else {
5138 tmp = rb_exec_recursive(file_inspect_join, ary, tmp);
5140 break;
5141 default:
5142 FilePathStringValue(tmp);
5143 checked = FALSE;
5145 RSTRING_GETMEM(result, name, len);
5146 if (i == 0) {
5147 rb_enc_copy(result, tmp);
5149 else {
5150 tail = chompdirsep(name, name + len, rb_enc_get(result));
5151 if (RSTRING_PTR(tmp) && isdirsep(RSTRING_PTR(tmp)[0])) {
5152 rb_str_set_len(result, tail - name);
5154 else if (!*tail) {
5155 rb_str_cat(result, "/", 1);
5158 enc = fs_enc_check(result, tmp);
5159 rb_str_buf_append(result, tmp);
5160 rb_enc_associate(result, enc);
5162 RBASIC_SET_CLASS_RAW(result, rb_cString);
5164 return result;
5168 * call-seq:
5169 * File.join(string, ...) -> string
5171 * Returns a new string formed by joining the strings using
5172 * <code>"/"</code>.
5174 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5178 static VALUE
5179 rb_file_s_join(VALUE klass, VALUE args)
5181 return rb_file_join(args);
5184 #if defined(HAVE_TRUNCATE)
5185 struct truncate_arg {
5186 const char *path;
5187 rb_off_t pos;
5190 static void *
5191 nogvl_truncate(void *ptr)
5193 struct truncate_arg *ta = ptr;
5194 return (void *)(VALUE)truncate(ta->path, ta->pos);
5198 * call-seq:
5199 * File.truncate(file_name, integer) -> 0
5201 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5202 * bytes long. Not available on all platforms.
5204 * f = File.new("out", "w")
5205 * f.write("1234567890") #=> 10
5206 * f.close #=> nil
5207 * File.truncate("out", 5) #=> 0
5208 * File.size("out") #=> 5
5212 static VALUE
5213 rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
5215 struct truncate_arg ta;
5216 int r;
5218 ta.pos = NUM2OFFT(len);
5219 FilePathValue(path);
5220 path = rb_str_encode_ospath(path);
5221 ta.path = StringValueCStr(path);
5223 r = IO_WITHOUT_GVL_INT(nogvl_truncate, &ta);
5224 if (r < 0)
5225 rb_sys_fail_path(path);
5226 return INT2FIX(0);
5228 #else
5229 #define rb_file_s_truncate rb_f_notimplement
5230 #endif
5232 #if defined(HAVE_FTRUNCATE)
5233 struct ftruncate_arg {
5234 int fd;
5235 rb_off_t pos;
5238 static VALUE
5239 nogvl_ftruncate(void *ptr)
5241 struct ftruncate_arg *fa = ptr;
5243 return (VALUE)ftruncate(fa->fd, fa->pos);
5247 * call-seq:
5248 * file.truncate(integer) -> 0
5250 * Truncates <i>file</i> to at most <i>integer</i> bytes. The file
5251 * must be opened for writing. Not available on all platforms.
5253 * f = File.new("out", "w")
5254 * f.syswrite("1234567890") #=> 10
5255 * f.truncate(5) #=> 0
5256 * f.close() #=> nil
5257 * File.size("out") #=> 5
5260 static VALUE
5261 rb_file_truncate(VALUE obj, VALUE len)
5263 rb_io_t *fptr;
5264 struct ftruncate_arg fa;
5266 fa.pos = NUM2OFFT(len);
5267 GetOpenFile(obj, fptr);
5268 if (!(fptr->mode & FMODE_WRITABLE)) {
5269 rb_raise(rb_eIOError, "not opened for writing");
5271 rb_io_flush_raw(obj, 0);
5272 fa.fd = fptr->fd;
5273 if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) {
5274 rb_sys_fail_path(fptr->pathv);
5276 return INT2FIX(0);
5278 #else
5279 #define rb_file_truncate rb_f_notimplement
5280 #endif
5282 # ifndef LOCK_SH
5283 # define LOCK_SH 1
5284 # endif
5285 # ifndef LOCK_EX
5286 # define LOCK_EX 2
5287 # endif
5288 # ifndef LOCK_NB
5289 # define LOCK_NB 4
5290 # endif
5291 # ifndef LOCK_UN
5292 # define LOCK_UN 8
5293 # endif
5295 #ifdef __CYGWIN__
5296 #include <winerror.h>
5297 #endif
5299 static VALUE
5300 rb_thread_flock(void *data)
5302 #ifdef __CYGWIN__
5303 int old_errno = errno;
5304 #endif
5305 int *op = data, ret = flock(op[0], op[1]);
5307 #ifdef __CYGWIN__
5308 if (GetLastError() == ERROR_NOT_LOCKED) {
5309 ret = 0;
5310 errno = old_errno;
5312 #endif
5313 return (VALUE)ret;
5316 /* :markup: markdown
5318 * call-seq:
5319 * flock(locking_constant) -> 0 or false
5321 * Locks or unlocks file +self+ according to the given `locking_constant`,
5322 * a bitwise OR of the values in the table below.
5324 * Not available on all platforms.
5326 * Returns `false` if `File::LOCK_NB` is specified and the operation would have blocked;
5327 * otherwise returns `0`.
5329 * <br>
5331 * | Constant | Lock | Effect
5332 * |-----------------|--------------|-------------------------------------------------------------------
5333 * | +File::LOCK_EX+ | Exclusive | Only one process may hold an exclusive lock for +self+ at a time.
5334 * | +File::LOCK_NB+ | Non-blocking | No blocking; may be combined with +File::LOCK_SH+ or +File::LOCK_EX+ using the bitwise OR operator <tt>\|</tt>.
5335 * | +File::LOCK_SH+ | Shared | Multiple processes may each hold a shared lock for +self+ at the same time.
5336 * | +File::LOCK_UN+ | Unlock | Remove an existing lock held by this process.
5338 * <br>
5340 * Example:
5342 * ```ruby
5343 * # Update a counter using an exclusive lock.
5344 * # Don't use File::WRONLY because it truncates the file.
5345 * File.open('counter', File::RDWR | File::CREAT, 0644) do |f|
5346 * f.flock(File::LOCK_EX)
5347 * value = f.read.to_i + 1
5348 * f.rewind
5349 * f.write("#{value}\n")
5350 * f.flush
5351 * f.truncate(f.pos)
5352 * end
5354 * # Read the counter using a shared lock.
5355 * File.open('counter', 'r') do |f|
5356 * f.flock(File::LOCK_SH)
5357 * f.read
5358 * end
5359 * ```
5363 static VALUE
5364 rb_file_flock(VALUE obj, VALUE operation)
5366 rb_io_t *fptr;
5367 int op[2], op1;
5368 struct timeval time;
5370 op[1] = op1 = NUM2INT(operation);
5371 GetOpenFile(obj, fptr);
5372 op[0] = fptr->fd;
5374 if (fptr->mode & FMODE_WRITABLE) {
5375 rb_io_flush_raw(obj, 0);
5377 while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) {
5378 int e = errno;
5379 switch (e) {
5380 case EAGAIN:
5381 case EACCES:
5382 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5383 case EWOULDBLOCK:
5384 #endif
5385 if (op1 & LOCK_NB) return Qfalse;
5387 time.tv_sec = 0;
5388 time.tv_usec = 100 * 1000; /* 0.1 sec */
5389 rb_thread_wait_for(time);
5390 rb_io_check_closed(fptr);
5391 continue;
5393 case EINTR:
5394 #if defined(ERESTART)
5395 case ERESTART:
5396 #endif
5397 break;
5399 default:
5400 rb_syserr_fail_path(e, fptr->pathv);
5403 return INT2FIX(0);
5406 static void
5407 test_check(int n, int argc, VALUE *argv)
5409 int i;
5411 n+=1;
5412 rb_check_arity(argc, n, n);
5413 for (i=1; i<n; i++) {
5414 if (!RB_TYPE_P(argv[i], T_FILE)) {
5415 FilePathValue(argv[i]);
5420 #define CHECK(n) test_check((n), argc, argv)
5423 * :markup: markdown
5425 * call-seq:
5426 * test(char, path0, path1 = nil) -> object
5428 * Performs a test on one or both of the <i>filesystem entities</i> at the given paths
5429 * `path0` and `path1`:
5431 * - Each path `path0` or `path1` points to a file, directory, device, pipe, etc.
5432 * - Character `char` selects a specific test.
5434 * The tests:
5436 * - Each of these tests operates only on the entity at `path0`,
5437 * and returns `true` or `false`;
5438 * for a non-existent entity, returns `false` (does not raise exception):
5440 * | Character | Test |
5441 * |:------------:|:--------------------------------------------------------------------------|
5442 * | <tt>'b'</tt> | Whether the entity is a block device. |
5443 * | <tt>'c'</tt> | Whether the entity is a character device. |
5444 * | <tt>'d'</tt> | Whether the entity is a directory. |
5445 * | <tt>'e'</tt> | Whether the entity is an existing entity. |
5446 * | <tt>'f'</tt> | Whether the entity is an existing regular file. |
5447 * | <tt>'g'</tt> | Whether the entity's setgid bit is set. |
5448 * | <tt>'G'</tt> | Whether the entity's group ownership is equal to the caller's. |
5449 * | <tt>'k'</tt> | Whether the entity's sticky bit is set. |
5450 * | <tt>'l'</tt> | Whether the entity is a symbolic link. |
5451 * | <tt>'o'</tt> | Whether the entity is owned by the caller's effective uid. |
5452 * | <tt>'O'</tt> | Like <tt>'o'</tt>, but uses the real uid (not the effective uid). |
5453 * | <tt>'p'</tt> | Whether the entity is a FIFO device (named pipe). |
5454 * | <tt>'r'</tt> | Whether the entity is readable by the caller's effecive uid/gid. |
5455 * | <tt>'R'</tt> | Like <tt>'r'</tt>, but uses the real uid/gid (not the effective uid/gid). |
5456 * | <tt>'S'</tt> | Whether the entity is a socket. |
5457 * | <tt>'u'</tt> | Whether the entity's setuid bit is set. |
5458 * | <tt>'w'</tt> | Whether the entity is writable by the caller's effective uid/gid. |
5459 * | <tt>'W'</tt> | Like <tt>'w'</tt>, but uses the real uid/gid (not the effective uid/gid). |
5460 * | <tt>'x'</tt> | Whether the entity is executable by the caller's effective uid/gid. |
5461 * | <tt>'X'</tt> | Like <tt>'x'</tt>, but uses the real uid/gid (not the effecive uid/git). |
5462 * | <tt>'z'</tt> | Whether the entity exists and is of length zero. |
5464 * - This test operates only on the entity at `path0`,
5465 * and returns an integer size or +nil+:
5467 * | Character | Test |
5468 * |:------------:|:---------------------------------------------------------------------------------------------|
5469 * | <tt>'s'</tt> | Returns positive integer size if the entity exists and has non-zero length, +nil+ otherwise. |
5471 * - Each of these tests operates only on the entity at `path0`,
5472 * and returns a Time object;
5473 * raises an exception if the entity does not exist:
5475 * | Character | Test |
5476 * |:------------:|:---------------------------------------|
5477 * | <tt>'A'</tt> | Last access time for the entity. |
5478 * | <tt>'C'</tt> | Last change time for the entity. |
5479 * | <tt>'M'</tt> | Last modification time for the entity. |
5481 * - Each of these tests operates on the modification time (`mtime`)
5482 * of each of the entities at `path0` and `path1`,
5483 * and returns a `true` or `false`;
5484 * returns `false` if either entity does not exist:
5486 * | Character | Test |
5487 * |:------------:|:----------------------------------------------------------------|
5488 * | <tt>'<'</tt> | Whether the `mtime` at `path0` is less than that at `path1`. |
5489 * | <tt>'='</tt> | Whether the `mtime` at `path0` is equal to that at `path1`. |
5490 * | <tt>'>'</tt> | Whether the `mtime` at `path0` is greater than that at `path1`. |
5492 * - This test operates on the content of each of the entities at `path0` and `path1`,
5493 * and returns a `true` or `false`;
5494 * returns `false` if either entity does not exist:
5496 * | Character | Test |
5497 * |:------------:|:----------------------------------------------|
5498 * | <tt>'-'</tt> | Whether the entities exist and are identical. |
5502 static VALUE
5503 rb_f_test(int argc, VALUE *argv, VALUE _)
5505 int cmd;
5507 if (argc == 0) rb_check_arity(argc, 2, 3);
5508 cmd = NUM2CHR(argv[0]);
5509 if (cmd == 0) {
5510 goto unknown;
5512 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
5513 CHECK(1);
5514 switch (cmd) {
5515 case 'b':
5516 return rb_file_blockdev_p(0, argv[1]);
5518 case 'c':
5519 return rb_file_chardev_p(0, argv[1]);
5521 case 'd':
5522 return rb_file_directory_p(0, argv[1]);
5524 case 'e':
5525 return rb_file_exist_p(0, argv[1]);
5527 case 'f':
5528 return rb_file_file_p(0, argv[1]);
5530 case 'g':
5531 return rb_file_sgid_p(0, argv[1]);
5533 case 'G':
5534 return rb_file_grpowned_p(0, argv[1]);
5536 case 'k':
5537 return rb_file_sticky_p(0, argv[1]);
5539 case 'l':
5540 return rb_file_symlink_p(0, argv[1]);
5542 case 'o':
5543 return rb_file_owned_p(0, argv[1]);
5545 case 'O':
5546 return rb_file_rowned_p(0, argv[1]);
5548 case 'p':
5549 return rb_file_pipe_p(0, argv[1]);
5551 case 'r':
5552 return rb_file_readable_p(0, argv[1]);
5554 case 'R':
5555 return rb_file_readable_real_p(0, argv[1]);
5557 case 's':
5558 return rb_file_size_p(0, argv[1]);
5560 case 'S':
5561 return rb_file_socket_p(0, argv[1]);
5563 case 'u':
5564 return rb_file_suid_p(0, argv[1]);
5566 case 'w':
5567 return rb_file_writable_p(0, argv[1]);
5569 case 'W':
5570 return rb_file_writable_real_p(0, argv[1]);
5572 case 'x':
5573 return rb_file_executable_p(0, argv[1]);
5575 case 'X':
5576 return rb_file_executable_real_p(0, argv[1]);
5578 case 'z':
5579 return rb_file_zero_p(0, argv[1]);
5583 if (strchr("MAC", cmd)) {
5584 struct stat st;
5585 VALUE fname = argv[1];
5587 CHECK(1);
5588 if (rb_stat(fname, &st) == -1) {
5589 int e = errno;
5590 FilePathValue(fname);
5591 rb_syserr_fail_path(e, fname);
5594 switch (cmd) {
5595 case 'A':
5596 return stat_atime(&st);
5597 case 'M':
5598 return stat_mtime(&st);
5599 case 'C':
5600 return stat_ctime(&st);
5604 if (cmd == '-') {
5605 CHECK(2);
5606 return rb_file_identical_p(0, argv[1], argv[2]);
5609 if (strchr("=<>", cmd)) {
5610 struct stat st1, st2;
5611 struct timespec t1, t2;
5613 CHECK(2);
5614 if (rb_stat(argv[1], &st1) < 0) return Qfalse;
5615 if (rb_stat(argv[2], &st2) < 0) return Qfalse;
5617 t1 = stat_mtimespec(&st1);
5618 t2 = stat_mtimespec(&st2);
5620 switch (cmd) {
5621 case '=':
5622 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
5623 return Qfalse;
5625 case '>':
5626 if (t1.tv_sec > t2.tv_sec) return Qtrue;
5627 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
5628 return Qfalse;
5630 case '<':
5631 if (t1.tv_sec < t2.tv_sec) return Qtrue;
5632 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
5633 return Qfalse;
5636 unknown:
5637 /* unknown command */
5638 if (ISPRINT(cmd)) {
5639 rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
5641 else {
5642 rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
5644 UNREACHABLE_RETURN(Qundef);
5649 * Document-class: File::Stat
5651 * Objects of class File::Stat encapsulate common status information
5652 * for File objects. The information is recorded at the moment the
5653 * File::Stat object is created; changes made to the file after that
5654 * point will not be reflected. File::Stat objects are returned by
5655 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5656 * methods return platform-specific values, and not all values are
5657 * meaningful on all systems. See also Kernel#test.
5660 static VALUE
5661 rb_stat_s_alloc(VALUE klass)
5663 return stat_new_0(klass, 0);
5667 * call-seq:
5669 * File::Stat.new(file_name) -> stat
5671 * Create a File::Stat object for the given file name (raising an
5672 * exception if the file doesn't exist).
5675 static VALUE
5676 rb_stat_init(VALUE obj, VALUE fname)
5678 struct stat st;
5680 FilePathValue(fname);
5681 fname = rb_str_encode_ospath(fname);
5682 if (STAT(StringValueCStr(fname), &st) == -1) {
5683 rb_sys_fail_path(fname);
5686 struct rb_stat *rb_st;
5687 TypedData_Get_Struct(obj, struct rb_stat, &stat_data_type, rb_st);
5689 rb_st->stat = st;
5690 rb_st->initialized = true;
5692 return Qnil;
5695 /* :nodoc: */
5696 static VALUE
5697 rb_stat_init_copy(VALUE copy, VALUE orig)
5699 if (!OBJ_INIT_COPY(copy, orig)) return copy;
5701 struct rb_stat *orig_rb_st;
5702 TypedData_Get_Struct(orig, struct rb_stat, &stat_data_type, orig_rb_st);
5704 struct rb_stat *copy_rb_st;
5705 TypedData_Get_Struct(copy, struct rb_stat, &stat_data_type, copy_rb_st);
5707 *copy_rb_st = *orig_rb_st;
5708 return copy;
5712 * call-seq:
5713 * stat.ftype -> string
5715 * Identifies the type of <i>stat</i>. The return string is one of:
5716 * ``<code>file</code>'', ``<code>directory</code>'',
5717 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5718 * ``<code>fifo</code>'', ``<code>link</code>'',
5719 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5721 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5725 static VALUE
5726 rb_stat_ftype(VALUE obj)
5728 return rb_file_ftype(get_stat(obj));
5732 * call-seq:
5733 * stat.directory? -> true or false
5735 * Returns <code>true</code> if <i>stat</i> is a directory,
5736 * <code>false</code> otherwise.
5738 * File.stat("testfile").directory? #=> false
5739 * File.stat(".").directory? #=> true
5742 static VALUE
5743 rb_stat_d(VALUE obj)
5745 if (S_ISDIR(get_stat(obj)->st_mode)) return Qtrue;
5746 return Qfalse;
5750 * call-seq:
5751 * stat.pipe? -> true or false
5753 * Returns <code>true</code> if the operating system supports pipes and
5754 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5757 static VALUE
5758 rb_stat_p(VALUE obj)
5760 #ifdef S_IFIFO
5761 if (S_ISFIFO(get_stat(obj)->st_mode)) return Qtrue;
5763 #endif
5764 return Qfalse;
5768 * call-seq:
5769 * stat.symlink? -> true or false
5771 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5772 * <code>false</code> if it isn't or if the operating system doesn't
5773 * support this feature. As File::stat automatically follows symbolic
5774 * links, #symlink? will always be <code>false</code> for an object
5775 * returned by File::stat.
5777 * File.symlink("testfile", "alink") #=> 0
5778 * File.stat("alink").symlink? #=> false
5779 * File.lstat("alink").symlink? #=> true
5783 static VALUE
5784 rb_stat_l(VALUE obj)
5786 #ifdef S_ISLNK
5787 if (S_ISLNK(get_stat(obj)->st_mode)) return Qtrue;
5788 #endif
5789 return Qfalse;
5793 * call-seq:
5794 * stat.socket? -> true or false
5796 * Returns <code>true</code> if <i>stat</i> is a socket,
5797 * <code>false</code> if it isn't or if the operating system doesn't
5798 * support this feature.
5800 * File.stat("testfile").socket? #=> false
5804 static VALUE
5805 rb_stat_S(VALUE obj)
5807 #ifdef S_ISSOCK
5808 if (S_ISSOCK(get_stat(obj)->st_mode)) return Qtrue;
5810 #endif
5811 return Qfalse;
5815 * call-seq:
5816 * stat.blockdev? -> true or false
5818 * Returns <code>true</code> if the file is a block device,
5819 * <code>false</code> if it isn't or if the operating system doesn't
5820 * support this feature.
5822 * File.stat("testfile").blockdev? #=> false
5823 * File.stat("/dev/hda1").blockdev? #=> true
5827 static VALUE
5828 rb_stat_b(VALUE obj)
5830 #ifdef S_ISBLK
5831 if (S_ISBLK(get_stat(obj)->st_mode)) return Qtrue;
5833 #endif
5834 return Qfalse;
5838 * call-seq:
5839 * stat.chardev? -> true or false
5841 * Returns <code>true</code> if the file is a character device,
5842 * <code>false</code> if it isn't or if the operating system doesn't
5843 * support this feature.
5845 * File.stat("/dev/tty").chardev? #=> true
5849 static VALUE
5850 rb_stat_c(VALUE obj)
5852 if (S_ISCHR(get_stat(obj)->st_mode)) return Qtrue;
5854 return Qfalse;
5858 * call-seq:
5859 * stat.owned? -> true or false
5861 * Returns <code>true</code> if the effective user id of the process is
5862 * the same as the owner of <i>stat</i>.
5864 * File.stat("testfile").owned? #=> true
5865 * File.stat("/etc/passwd").owned? #=> false
5869 static VALUE
5870 rb_stat_owned(VALUE obj)
5872 if (get_stat(obj)->st_uid == geteuid()) return Qtrue;
5873 return Qfalse;
5876 static VALUE
5877 rb_stat_rowned(VALUE obj)
5879 if (get_stat(obj)->st_uid == getuid()) return Qtrue;
5880 return Qfalse;
5884 * call-seq:
5885 * stat.grpowned? -> true or false
5887 * Returns true if the effective group id of the process is the same as
5888 * the group id of <i>stat</i>. On Windows, returns <code>false</code>.
5890 * File.stat("testfile").grpowned? #=> true
5891 * File.stat("/etc/passwd").grpowned? #=> false
5895 static VALUE
5896 rb_stat_grpowned(VALUE obj)
5898 #ifndef _WIN32
5899 if (rb_group_member(get_stat(obj)->st_gid)) return Qtrue;
5900 #endif
5901 return Qfalse;
5905 * call-seq:
5906 * stat.readable? -> true or false
5908 * Returns <code>true</code> if <i>stat</i> is readable by the
5909 * effective user id of this process.
5911 * File.stat("testfile").readable? #=> true
5915 static VALUE
5916 rb_stat_r(VALUE obj)
5918 struct stat *st = get_stat(obj);
5920 #ifdef USE_GETEUID
5921 if (geteuid() == 0) return Qtrue;
5922 #endif
5923 #ifdef S_IRUSR
5924 if (rb_stat_owned(obj))
5925 return RBOOL(st->st_mode & S_IRUSR);
5926 #endif
5927 #ifdef S_IRGRP
5928 if (rb_stat_grpowned(obj))
5929 return RBOOL(st->st_mode & S_IRGRP);
5930 #endif
5931 #ifdef S_IROTH
5932 if (!(st->st_mode & S_IROTH)) return Qfalse;
5933 #endif
5934 return Qtrue;
5938 * call-seq:
5939 * stat.readable_real? -> true or false
5941 * Returns <code>true</code> if <i>stat</i> is readable by the real
5942 * user id of this process.
5944 * File.stat("testfile").readable_real? #=> true
5948 static VALUE
5949 rb_stat_R(VALUE obj)
5951 struct stat *st = get_stat(obj);
5953 #ifdef USE_GETEUID
5954 if (getuid() == 0) return Qtrue;
5955 #endif
5956 #ifdef S_IRUSR
5957 if (rb_stat_rowned(obj))
5958 return RBOOL(st->st_mode & S_IRUSR);
5959 #endif
5960 #ifdef S_IRGRP
5961 if (rb_group_member(get_stat(obj)->st_gid))
5962 return RBOOL(st->st_mode & S_IRGRP);
5963 #endif
5964 #ifdef S_IROTH
5965 if (!(st->st_mode & S_IROTH)) return Qfalse;
5966 #endif
5967 return Qtrue;
5971 * call-seq:
5972 * stat.world_readable? -> integer or nil
5974 * If <i>stat</i> is readable by others, returns an integer
5975 * representing the file permission bits of <i>stat</i>. Returns
5976 * <code>nil</code> otherwise. The meaning of the bits is platform
5977 * dependent; on Unix systems, see <code>stat(2)</code>.
5979 * m = File.stat("/etc/passwd").world_readable? #=> 420
5980 * sprintf("%o", m) #=> "644"
5983 static VALUE
5984 rb_stat_wr(VALUE obj)
5986 #ifdef S_IROTH
5987 struct stat *st = get_stat(obj);
5988 if ((st->st_mode & (S_IROTH)) == S_IROTH) {
5989 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
5991 #endif
5992 return Qnil;
5996 * call-seq:
5997 * stat.writable? -> true or false
5999 * Returns <code>true</code> if <i>stat</i> is writable by the
6000 * effective user id of this process.
6002 * File.stat("testfile").writable? #=> true
6006 static VALUE
6007 rb_stat_w(VALUE obj)
6009 struct stat *st = get_stat(obj);
6011 #ifdef USE_GETEUID
6012 if (geteuid() == 0) return Qtrue;
6013 #endif
6014 #ifdef S_IWUSR
6015 if (rb_stat_owned(obj))
6016 return RBOOL(st->st_mode & S_IWUSR);
6017 #endif
6018 #ifdef S_IWGRP
6019 if (rb_stat_grpowned(obj))
6020 return RBOOL(st->st_mode & S_IWGRP);
6021 #endif
6022 #ifdef S_IWOTH
6023 if (!(st->st_mode & S_IWOTH)) return Qfalse;
6024 #endif
6025 return Qtrue;
6029 * call-seq:
6030 * stat.writable_real? -> true or false
6032 * Returns <code>true</code> if <i>stat</i> is writable by the real
6033 * user id of this process.
6035 * File.stat("testfile").writable_real? #=> true
6039 static VALUE
6040 rb_stat_W(VALUE obj)
6042 struct stat *st = get_stat(obj);
6044 #ifdef USE_GETEUID
6045 if (getuid() == 0) return Qtrue;
6046 #endif
6047 #ifdef S_IWUSR
6048 if (rb_stat_rowned(obj))
6049 return RBOOL(st->st_mode & S_IWUSR);
6050 #endif
6051 #ifdef S_IWGRP
6052 if (rb_group_member(get_stat(obj)->st_gid))
6053 return RBOOL(st->st_mode & S_IWGRP);
6054 #endif
6055 #ifdef S_IWOTH
6056 if (!(st->st_mode & S_IWOTH)) return Qfalse;
6057 #endif
6058 return Qtrue;
6062 * call-seq:
6063 * stat.world_writable? -> integer or nil
6065 * If <i>stat</i> is writable by others, returns an integer
6066 * representing the file permission bits of <i>stat</i>. Returns
6067 * <code>nil</code> otherwise. The meaning of the bits is platform
6068 * dependent; on Unix systems, see <code>stat(2)</code>.
6070 * m = File.stat("/tmp").world_writable? #=> 511
6071 * sprintf("%o", m) #=> "777"
6074 static VALUE
6075 rb_stat_ww(VALUE obj)
6077 #ifdef S_IWOTH
6078 struct stat *st = get_stat(obj);
6079 if ((st->st_mode & (S_IWOTH)) == S_IWOTH) {
6080 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
6082 #endif
6083 return Qnil;
6087 * call-seq:
6088 * stat.executable? -> true or false
6090 * Returns <code>true</code> if <i>stat</i> is executable or if the
6091 * operating system doesn't distinguish executable files from
6092 * nonexecutable files. The tests are made using the effective owner of
6093 * the process.
6095 * File.stat("testfile").executable? #=> false
6099 static VALUE
6100 rb_stat_x(VALUE obj)
6102 struct stat *st = get_stat(obj);
6104 #ifdef USE_GETEUID
6105 if (geteuid() == 0) {
6106 return RBOOL(st->st_mode & S_IXUGO);
6108 #endif
6109 #ifdef S_IXUSR
6110 if (rb_stat_owned(obj))
6111 return RBOOL(st->st_mode & S_IXUSR);
6112 #endif
6113 #ifdef S_IXGRP
6114 if (rb_stat_grpowned(obj))
6115 return RBOOL(st->st_mode & S_IXGRP);
6116 #endif
6117 #ifdef S_IXOTH
6118 if (!(st->st_mode & S_IXOTH)) return Qfalse;
6119 #endif
6120 return Qtrue;
6124 * call-seq:
6125 * stat.executable_real? -> true or false
6127 * Same as <code>executable?</code>, but tests using the real owner of
6128 * the process.
6131 static VALUE
6132 rb_stat_X(VALUE obj)
6134 struct stat *st = get_stat(obj);
6136 #ifdef USE_GETEUID
6137 if (getuid() == 0) {
6138 return RBOOL(st->st_mode & S_IXUGO);
6140 #endif
6141 #ifdef S_IXUSR
6142 if (rb_stat_rowned(obj))
6143 return RBOOL(st->st_mode & S_IXUSR);
6144 #endif
6145 #ifdef S_IXGRP
6146 if (rb_group_member(get_stat(obj)->st_gid))
6147 return RBOOL(st->st_mode & S_IXGRP);
6148 #endif
6149 #ifdef S_IXOTH
6150 if (!(st->st_mode & S_IXOTH)) return Qfalse;
6151 #endif
6152 return Qtrue;
6156 * call-seq:
6157 * stat.file? -> true or false
6159 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6160 * a device file, pipe, socket, etc.).
6162 * File.stat("testfile").file? #=> true
6166 static VALUE
6167 rb_stat_f(VALUE obj)
6169 if (S_ISREG(get_stat(obj)->st_mode)) return Qtrue;
6170 return Qfalse;
6174 * call-seq:
6175 * stat.zero? -> true or false
6177 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6178 * <code>false</code> otherwise.
6180 * File.stat("testfile").zero? #=> false
6184 static VALUE
6185 rb_stat_z(VALUE obj)
6187 if (get_stat(obj)->st_size == 0) return Qtrue;
6188 return Qfalse;
6192 * call-seq:
6193 * stat.size? -> Integer or nil
6195 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6196 * the file otherwise.
6198 * File.stat("testfile").size? #=> 66
6199 * File.stat(File::NULL).size? #=> nil
6203 static VALUE
6204 rb_stat_s(VALUE obj)
6206 rb_off_t size = get_stat(obj)->st_size;
6208 if (size == 0) return Qnil;
6209 return OFFT2NUM(size);
6213 * call-seq:
6214 * stat.setuid? -> true or false
6216 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6217 * permission bit set, <code>false</code> if it doesn't or if the
6218 * operating system doesn't support this feature.
6220 * File.stat("/bin/su").setuid? #=> true
6223 static VALUE
6224 rb_stat_suid(VALUE obj)
6226 #ifdef S_ISUID
6227 if (get_stat(obj)->st_mode & S_ISUID) return Qtrue;
6228 #endif
6229 return Qfalse;
6233 * call-seq:
6234 * stat.setgid? -> true or false
6236 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6237 * permission bit set, <code>false</code> if it doesn't or if the
6238 * operating system doesn't support this feature.
6240 * File.stat("/usr/sbin/lpc").setgid? #=> true
6244 static VALUE
6245 rb_stat_sgid(VALUE obj)
6247 #ifdef S_ISGID
6248 if (get_stat(obj)->st_mode & S_ISGID) return Qtrue;
6249 #endif
6250 return Qfalse;
6254 * call-seq:
6255 * stat.sticky? -> true or false
6257 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6258 * <code>false</code> if it doesn't or if the operating system doesn't
6259 * support this feature.
6261 * File.stat("testfile").sticky? #=> false
6265 static VALUE
6266 rb_stat_sticky(VALUE obj)
6268 #ifdef S_ISVTX
6269 if (get_stat(obj)->st_mode & S_ISVTX) return Qtrue;
6270 #endif
6271 return Qfalse;
6274 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6275 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6276 #define HAVE_MKFIFO
6277 #endif
6279 #ifdef HAVE_MKFIFO
6280 struct mkfifo_arg {
6281 const char *path;
6282 mode_t mode;
6285 static void *
6286 nogvl_mkfifo(void *ptr)
6288 struct mkfifo_arg *ma = ptr;
6290 return (void *)(VALUE)mkfifo(ma->path, ma->mode);
6294 * call-seq:
6295 * File.mkfifo(file_name, mode=0666) => 0
6297 * Creates a FIFO special file with name _file_name_. _mode_
6298 * specifies the FIFO's permissions. It is modified by the process's
6299 * umask in the usual way: the permissions of the created file are
6300 * (mode & ~umask).
6303 static VALUE
6304 rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _)
6306 VALUE path;
6307 struct mkfifo_arg ma;
6309 ma.mode = 0666;
6310 rb_check_arity(argc, 1, 2);
6311 if (argc > 1) {
6312 ma.mode = NUM2MODET(argv[1]);
6314 path = argv[0];
6315 FilePathValue(path);
6316 path = rb_str_encode_ospath(path);
6317 ma.path = RSTRING_PTR(path);
6318 if (IO_WITHOUT_GVL(nogvl_mkfifo, &ma)) {
6319 rb_sys_fail_path(path);
6321 return INT2FIX(0);
6323 #else
6324 #define rb_file_s_mkfifo rb_f_notimplement
6325 #endif
6327 static VALUE rb_mFConst;
6329 void
6330 rb_file_const(const char *name, VALUE value)
6332 rb_define_const(rb_mFConst, name, value);
6336 rb_is_absolute_path(const char *path)
6338 #ifdef DOSISH_DRIVE_LETTER
6339 if (has_drive_letter(path) && isdirsep(path[2])) return 1;
6340 #endif
6341 #ifdef DOSISH_UNC
6342 if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
6343 #endif
6344 #ifndef DOSISH
6345 if (path[0] == '/') return 1;
6346 #endif
6347 return 0;
6350 #ifndef ENABLE_PATH_CHECK
6351 # if defined DOSISH || defined __CYGWIN__
6352 # define ENABLE_PATH_CHECK 0
6353 # else
6354 # define ENABLE_PATH_CHECK 1
6355 # endif
6356 #endif
6358 #if ENABLE_PATH_CHECK
6359 static int
6360 path_check_0(VALUE path)
6362 struct stat st;
6363 const char *p0 = StringValueCStr(path);
6364 const char *e0;
6365 rb_encoding *enc;
6366 char *p = 0, *s;
6368 if (!rb_is_absolute_path(p0)) {
6369 char *buf = ruby_getcwd();
6370 VALUE newpath;
6372 newpath = rb_str_new2(buf);
6373 xfree(buf);
6375 rb_str_cat2(newpath, "/");
6376 rb_str_cat2(newpath, p0);
6377 path = newpath;
6378 p0 = RSTRING_PTR(path);
6380 e0 = p0 + RSTRING_LEN(path);
6381 enc = rb_enc_get(path);
6382 for (;;) {
6383 #ifndef S_IWOTH
6384 # define S_IWOTH 002
6385 #endif
6386 if (STAT(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH)
6387 #ifdef S_ISVTX
6388 && !(p && (st.st_mode & S_ISVTX))
6389 #endif
6390 && !access(p0, W_OK)) {
6391 rb_enc_warn(enc, "Insecure world writable dir %s in PATH, mode 0%"
6392 #if SIZEOF_DEV_T > SIZEOF_INT
6393 PRI_MODET_PREFIX"o",
6394 #else
6395 "o",
6396 #endif
6397 p0, st.st_mode);
6398 if (p) *p = '/';
6399 RB_GC_GUARD(path);
6400 return 0;
6402 s = strrdirsep(p0, e0, enc);
6403 if (p) *p = '/';
6404 if (!s || s == p0) return 1;
6405 p = s;
6406 e0 = p;
6407 *p = '\0';
6410 #endif
6413 rb_path_check(const char *path)
6415 #if ENABLE_PATH_CHECK
6416 const char *p0, *p, *pend;
6417 const char sep = PATH_SEP_CHAR;
6419 if (!path) return 1;
6421 pend = path + strlen(path);
6422 p0 = path;
6423 p = strchr(path, sep);
6424 if (!p) p = pend;
6426 for (;;) {
6427 if (!path_check_0(rb_str_new(p0, p - p0))) {
6428 return 0; /* not safe */
6430 p0 = p + 1;
6431 if (p0 > pend) break;
6432 p = strchr(p0, sep);
6433 if (!p) p = pend;
6435 #endif
6436 return 1;
6440 ruby_is_fd_loadable(int fd)
6442 #ifdef _WIN32
6443 return 1;
6444 #else
6445 struct stat st;
6447 if (fstat(fd, &st) < 0)
6448 return 0;
6450 if (S_ISREG(st.st_mode))
6451 return 1;
6453 if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
6454 return -1;
6456 if (S_ISDIR(st.st_mode))
6457 errno = EISDIR;
6458 else
6459 errno = ENXIO;
6461 return 0;
6462 #endif
6465 #ifndef _WIN32
6467 rb_file_load_ok(const char *path)
6469 int ret = 1;
6471 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6472 FIXME: Why O_NDELAY is checked?
6474 int mode = (O_RDONLY |
6475 #if defined O_NONBLOCK
6476 O_NONBLOCK |
6477 #elif defined O_NDELAY
6478 O_NDELAY |
6479 #endif
6481 int fd = rb_cloexec_open(path, mode, 0);
6482 if (fd < 0) {
6483 if (!rb_gc_for_fd(errno)) return 0;
6484 fd = rb_cloexec_open(path, mode, 0);
6485 if (fd < 0) return 0;
6487 rb_update_max_fd(fd);
6488 ret = ruby_is_fd_loadable(fd);
6489 (void)close(fd);
6490 return ret;
6492 #endif
6494 static int
6495 is_explicit_relative(const char *path)
6497 if (*path++ != '.') return 0;
6498 if (*path == '.') path++;
6499 return isdirsep(*path);
6502 static VALUE
6503 copy_path_class(VALUE path, VALUE orig)
6505 int encidx = rb_enc_get_index(orig);
6506 if (encidx == ENCINDEX_ASCII_8BIT || encidx == ENCINDEX_US_ASCII)
6507 encidx = rb_filesystem_encindex();
6508 rb_enc_associate_index(path, encidx);
6509 str_shrink(path);
6510 RBASIC_SET_CLASS(path, rb_obj_class(orig));
6511 OBJ_FREEZE(path);
6512 return path;
6516 rb_find_file_ext(VALUE *filep, const char *const *ext)
6518 const char *f = StringValueCStr(*filep);
6519 VALUE fname = *filep, load_path, tmp;
6520 long i, j, fnlen;
6521 int expanded = 0;
6523 if (!ext[0]) return 0;
6525 if (f[0] == '~') {
6526 fname = file_expand_path_1(fname);
6527 f = RSTRING_PTR(fname);
6528 *filep = fname;
6529 expanded = 1;
6532 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6533 if (!expanded) fname = file_expand_path_1(fname);
6534 fnlen = RSTRING_LEN(fname);
6535 for (i=0; ext[i]; i++) {
6536 rb_str_cat2(fname, ext[i]);
6537 if (rb_file_load_ok(RSTRING_PTR(fname))) {
6538 *filep = copy_path_class(fname, *filep);
6539 return (int)(i+1);
6541 rb_str_set_len(fname, fnlen);
6543 return 0;
6546 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6547 if (!load_path) return 0;
6549 fname = rb_str_dup(*filep);
6550 RBASIC_CLEAR_CLASS(fname);
6551 fnlen = RSTRING_LEN(fname);
6552 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6553 rb_enc_associate_index(tmp, rb_usascii_encindex());
6554 for (j=0; ext[j]; j++) {
6555 rb_str_cat2(fname, ext[j]);
6556 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6557 VALUE str = RARRAY_AREF(load_path, i);
6559 RB_GC_GUARD(str) = rb_get_path(str);
6560 if (RSTRING_LEN(str) == 0) continue;
6561 rb_file_expand_path_internal(fname, str, 0, 0, tmp);
6562 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
6563 *filep = copy_path_class(tmp, *filep);
6564 return (int)(j+1);
6567 rb_str_set_len(fname, fnlen);
6569 rb_str_resize(tmp, 0);
6570 RB_GC_GUARD(load_path);
6571 return 0;
6574 VALUE
6575 rb_find_file(VALUE path)
6577 VALUE tmp, load_path;
6578 const char *f = StringValueCStr(path);
6579 int expanded = 0;
6581 if (f[0] == '~') {
6582 tmp = file_expand_path_1(path);
6583 path = copy_path_class(tmp, path);
6584 f = RSTRING_PTR(path);
6585 expanded = 1;
6588 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6589 if (!rb_file_load_ok(f)) return 0;
6590 if (!expanded)
6591 path = copy_path_class(file_expand_path_1(path), path);
6592 return path;
6595 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6596 if (load_path) {
6597 long i;
6599 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6600 rb_enc_associate_index(tmp, rb_usascii_encindex());
6601 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6602 VALUE str = RARRAY_AREF(load_path, i);
6603 RB_GC_GUARD(str) = rb_get_path(str);
6604 if (RSTRING_LEN(str) > 0) {
6605 rb_file_expand_path_internal(path, str, 0, 0, tmp);
6606 f = RSTRING_PTR(tmp);
6607 if (rb_file_load_ok(f)) goto found;
6610 rb_str_resize(tmp, 0);
6611 return 0;
6613 else {
6614 return 0; /* no path, no load */
6617 found:
6618 return copy_path_class(tmp, path);
6621 #define define_filetest_function(name, func, argc) do { \
6622 rb_define_module_function(rb_mFileTest, name, func, argc); \
6623 rb_define_singleton_method(rb_cFile, name, func, argc); \
6624 } while(false)
6626 const char ruby_null_device[] =
6627 #if defined DOSISH
6628 "NUL"
6629 #elif defined AMIGA || defined __amigaos__
6630 "NIL"
6631 #elif defined __VMS
6632 "NL:"
6633 #else
6634 "/dev/null"
6635 #endif
6639 * A \File object is a representation of a file in the underlying platform.
6641 * \Class \File extends module FileTest, supporting such singleton methods
6642 * as <tt>File.exist?</tt>.
6644 * == About the Examples
6646 * Many examples here use these variables:
6648 * :include: doc/examples/files.rdoc
6650 * == Access Modes
6652 * Methods File.new and File.open each create a \File object for a given file path.
6654 * === \String Access Modes
6656 * Methods File.new and File.open each may take string argument +mode+, which:
6658 * - Begins with a 1- or 2-character
6659 * {read/write mode}[rdoc-ref:File@Read-2FWrite+Mode].
6660 * - May also contain a 1-character {data mode}[rdoc-ref:File@Data+Mode].
6661 * - May also contain a 1-character
6662 * {file-create mode}[rdoc-ref:File@File-Create+Mode].
6664 * ==== Read/Write Mode
6666 * The read/write +mode+ determines:
6668 * - Whether the file is to be initially truncated.
6670 * - Whether reading is allowed, and if so:
6672 * - The initial read position in the file.
6673 * - Where in the file reading can occur.
6675 * - Whether writing is allowed, and if so:
6677 * - The initial write position in the file.
6678 * - Where in the file writing can occur.
6680 * These tables summarize:
6682 * Read/Write Modes for Existing File
6684 * |------|-----------|----------|----------|----------|-----------|
6685 * | R/W | Initial | | Initial | | Initial |
6686 * | Mode | Truncate? | Read | Read Pos | Write | Write Pos |
6687 * |------|-----------|----------|----------|----------|-----------|
6688 * | 'r' | No | Anywhere | 0 | Error | - |
6689 * | 'w' | Yes | Error | - | Anywhere | 0 |
6690 * | 'a' | No | Error | - | End only | End |
6691 * | 'r+' | No | Anywhere | 0 | Anywhere | 0 |
6692 * | 'w+' | Yes | Anywhere | 0 | Anywhere | 0 |
6693 * | 'a+' | No | Anywhere | End | End only | End |
6694 * |------|-----------|----------|----------|----------|-----------|
6696 * Read/Write Modes for \File To Be Created
6698 * |------|----------|----------|----------|-----------|
6699 * | R/W | | Initial | | Initial |
6700 * | Mode | Read | Read Pos | Write | Write Pos |
6701 * |------|----------|----------|----------|-----------|
6702 * | 'w' | Error | - | Anywhere | 0 |
6703 * | 'a' | Error | - | End only | 0 |
6704 * | 'w+' | Anywhere | 0 | Anywhere | 0 |
6705 * | 'a+' | Anywhere | 0 | End only | End |
6706 * |------|----------|----------|----------|-----------|
6708 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
6709 * for a non-existent file (exception raised).
6711 * In the tables:
6713 * - +Anywhere+ means that methods IO#rewind, IO#pos=, and IO#seek
6714 * may be used to change the file's position,
6715 * so that allowed reading or writing may occur anywhere in the file.
6716 * - <tt>End only</tt> means that writing can occur only at end-of-file,
6717 * and that methods IO#rewind, IO#pos=, and IO#seek do not affect writing.
6718 * - +Error+ means that an exception is raised if disallowed reading or writing
6719 * is attempted.
6721 * ===== Read/Write Modes for Existing \File
6723 * - <tt>'r'</tt>:
6725 * - \File is not initially truncated:
6727 * f = File.new('t.txt') # => #<File:t.txt>
6728 * f.size == 0 # => false
6730 * - File's initial read position is 0:
6732 * f.pos # => 0
6734 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
6736 * f.readline # => "First line\n"
6737 * f.readline # => "Second line\n"
6739 * f.rewind
6740 * f.readline # => "First line\n"
6742 * f.pos = 1
6743 * f.readline # => "irst line\n"
6745 * f.seek(1, :CUR)
6746 * f.readline # => "econd line\n"
6748 * - Writing is not allowed:
6750 * f.write('foo') # Raises IOError.
6752 * - <tt>'w'</tt>:
6754 * - \File is initially truncated:
6756 * path = 't.tmp'
6757 * File.write(path, text)
6758 * f = File.new(path, 'w')
6759 * f.size == 0 # => true
6761 * - File's initial write position is 0:
6763 * f.pos # => 0
6765 * - \File may be written anywhere (even past end-of-file);
6766 * see IO#rewind, IO#pos=, IO#seek:
6768 * f.write('foo')
6769 * f.flush
6770 * File.read(path) # => "foo"
6771 * f.pos # => 3
6773 * f.write('bar')
6774 * f.flush
6775 * File.read(path) # => "foobar"
6776 * f.pos # => 6
6778 * f.rewind
6779 * f.write('baz')
6780 * f.flush
6781 * File.read(path) # => "bazbar"
6782 * f.pos # => 3
6784 * f.pos = 3
6785 * f.write('foo')
6786 * f.flush
6787 * File.read(path) # => "bazfoo"
6788 * f.pos # => 6
6790 * f.seek(-3, :END)
6791 * f.write('bam')
6792 * f.flush
6793 * File.read(path) # => "bazbam"
6794 * f.pos # => 6
6796 * f.pos = 8
6797 * f.write('bah') # Zero padding as needed.
6798 * f.flush
6799 * File.read(path) # => "bazbam\u0000\u0000bah"
6800 * f.pos # => 11
6802 * - Reading is not allowed:
6804 * f.read # Raises IOError.
6806 * - <tt>'a'</tt>:
6808 * - \File is not initially truncated:
6810 * path = 't.tmp'
6811 * File.write(path, 'foo')
6812 * f = File.new(path, 'a')
6813 * f.size == 0 # => false
6815 * - File's initial position is 0 (but is ignored):
6817 * f.pos # => 0
6819 * - \File may be written only at end-of-file;
6820 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6822 * f.write('bar')
6823 * f.flush
6824 * File.read(path) # => "foobar"
6825 * f.write('baz')
6826 * f.flush
6827 * File.read(path) # => "foobarbaz"
6829 * f.rewind
6830 * f.write('bat')
6831 * f.flush
6832 * File.read(path) # => "foobarbazbat"
6834 * - Reading is not allowed:
6836 * f.read # Raises IOError.
6838 * - <tt>'r+'</tt>:
6840 * - \File is not initially truncated:
6842 * path = 't.tmp'
6843 * File.write(path, text)
6844 * f = File.new(path, 'r+')
6845 * f.size == 0 # => false
6847 * - File's initial read position is 0:
6849 * f.pos # => 0
6851 * - \File may be read or written anywhere (even past end-of-file);
6852 * see IO#rewind, IO#pos=, IO#seek:
6854 * f.readline # => "First line\n"
6855 * f.readline # => "Second line\n"
6857 * f.rewind
6858 * f.readline # => "First line\n"
6860 * f.pos = 1
6861 * f.readline # => "irst line\n"
6863 * f.seek(1, :CUR)
6864 * f.readline # => "econd line\n"
6866 * f.rewind
6867 * f.write('WWW')
6868 * f.flush
6869 * File.read(path)
6870 * # => "WWWst line\nSecond line\nFourth line\nFifth line\n"
6872 * f.pos = 10
6873 * f.write('XXX')
6874 * f.flush
6875 * File.read(path)
6876 * # => "WWWst lineXXXecond line\nFourth line\nFifth line\n"
6878 * f.seek(-6, :END)
6879 * # => 0
6880 * f.write('YYY')
6881 * # => 3
6882 * f.flush
6883 * # => #<File:t.tmp>
6884 * File.read(path)
6885 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n"
6887 * f.seek(2, :END)
6888 * f.write('ZZZ') # Zero padding as needed.
6889 * f.flush
6890 * File.read(path)
6891 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
6894 * - <tt>'a+'</tt>:
6896 * - \File is not initially truncated:
6898 * path = 't.tmp'
6899 * File.write(path, 'foo')
6900 * f = File.new(path, 'a+')
6901 * f.size == 0 # => false
6903 * - File's initial read position is 0:
6905 * f.pos # => 0
6907 * - \File may be written only at end-of-file;
6908 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6910 * f.write('bar')
6911 * f.flush
6912 * File.read(path) # => "foobar"
6913 * f.write('baz')
6914 * f.flush
6915 * File.read(path) # => "foobarbaz"
6917 * f.rewind
6918 * f.write('bat')
6919 * f.flush
6920 * File.read(path) # => "foobarbazbat"
6922 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
6924 * f.rewind
6925 * f.read # => "foobarbazbat"
6927 * f.pos = 3
6928 * f.read # => "barbazbat"
6930 * f.seek(-3, :END)
6931 * f.read # => "bat"
6933 * ===== Read/Write Modes for \File To Be Created
6935 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
6936 * for a non-existent file (exception raised).
6938 * - <tt>'w'</tt>:
6940 * - File's initial write position is 0:
6942 * path = 't.tmp'
6943 * FileUtils.rm_f(path)
6944 * f = File.new(path, 'w')
6945 * f.pos # => 0
6947 * - \File may be written anywhere (even past end-of-file);
6948 * see IO#rewind, IO#pos=, IO#seek:
6950 * f.write('foo')
6951 * f.flush
6952 * File.read(path) # => "foo"
6953 * f.pos # => 3
6955 * f.write('bar')
6956 * f.flush
6957 * File.read(path) # => "foobar"
6958 * f.pos # => 6
6960 * f.rewind
6961 * f.write('baz')
6962 * f.flush
6963 * File.read(path) # => "bazbar"
6964 * f.pos # => 3
6966 * f.pos = 3
6967 * f.write('foo')
6968 * f.flush
6969 * File.read(path) # => "bazfoo"
6970 * f.pos # => 6
6972 * f.seek(-3, :END)
6973 * f.write('bam')
6974 * f.flush
6975 * File.read(path) # => "bazbam"
6976 * f.pos # => 6
6978 * f.pos = 8
6979 * f.write('bah') # Zero padding as needed.
6980 * f.flush
6981 * File.read(path) # => "bazbam\u0000\u0000bah"
6982 * f.pos # => 11
6984 * - Reading is not allowed:
6986 * f.read # Raises IOError.
6988 * - <tt>'a'</tt>:
6990 * - File's initial write position is 0:
6992 * path = 't.tmp'
6993 * FileUtils.rm_f(path)
6994 * f = File.new(path, 'a')
6995 * f.pos # => 0
6997 * - Writing occurs only at end-of-file:
6999 * f.write('foo')
7000 * f.pos # => 3
7001 * f.write('bar')
7002 * f.pos # => 6
7003 * f.flush
7004 * File.read(path) # => "foobar"
7006 * f.rewind
7007 * f.write('baz')
7008 * f.flush
7009 * File.read(path) # => "foobarbaz"
7011 * - Reading is not allowed:
7013 * f.read # Raises IOError.
7015 * - <tt>'w+'</tt>:
7017 * - File's initial position is 0:
7019 * path = 't.tmp'
7020 * FileUtils.rm_f(path)
7021 * f = File.new(path, 'w+')
7022 * f.pos # => 0
7024 * - \File may be written anywhere (even past end-of-file);
7025 * see IO#rewind, IO#pos=, IO#seek:
7027 * f.write('foo')
7028 * f.flush
7029 * File.read(path) # => "foo"
7030 * f.pos # => 3
7032 * f.write('bar')
7033 * f.flush
7034 * File.read(path) # => "foobar"
7035 * f.pos # => 6
7037 * f.rewind
7038 * f.write('baz')
7039 * f.flush
7040 * File.read(path) # => "bazbar"
7041 * f.pos # => 3
7043 * f.pos = 3
7044 * f.write('foo')
7045 * f.flush
7046 * File.read(path) # => "bazfoo"
7047 * f.pos # => 6
7049 * f.seek(-3, :END)
7050 * f.write('bam')
7051 * f.flush
7052 * File.read(path) # => "bazbam"
7053 * f.pos # => 6
7055 * f.pos = 8
7056 * f.write('bah') # Zero padding as needed.
7057 * f.flush
7058 * File.read(path) # => "bazbam\u0000\u0000bah"
7059 * f.pos # => 11
7061 * - \File may be read anywhere (even past end-of-file);
7062 * see IO#rewind, IO#pos=, IO#seek:
7064 * f.rewind
7065 * # => 0
7066 * f.read
7067 * # => "bazbam\u0000\u0000bah"
7069 * f.pos = 3
7070 * # => 3
7071 * f.read
7072 * # => "bam\u0000\u0000bah"
7074 * f.seek(-3, :END)
7075 * # => 0
7076 * f.read
7077 * # => "bah"
7079 * - <tt>'a+'</tt>:
7081 * - File's initial write position is 0:
7083 * path = 't.tmp'
7084 * FileUtils.rm_f(path)
7085 * f = File.new(path, 'a+')
7086 * f.pos # => 0
7088 * - Writing occurs only at end-of-file:
7090 * f.write('foo')
7091 * f.pos # => 3
7092 * f.write('bar')
7093 * f.pos # => 6
7094 * f.flush
7095 * File.read(path) # => "foobar"
7097 * f.rewind
7098 * f.write('baz')
7099 * f.flush
7100 * File.read(path) # => "foobarbaz"
7102 * - \File may be read anywhere (even past end-of-file);
7103 * see IO#rewind, IO#pos=, IO#seek:
7105 * f.rewind
7106 * f.read # => "foobarbaz"
7108 * f.pos = 3
7109 * f.read # => "barbaz"
7111 * f.seek(-3, :END)
7112 * f.read # => "baz"
7114 * f.pos = 800
7115 * f.read # => ""
7117 * ==== \Data Mode
7119 * To specify whether data is to be treated as text or as binary data,
7120 * either of the following may be suffixed to any of the string read/write modes
7121 * above:
7123 * - <tt>'t'</tt>: Text data; sets the default external encoding
7124 * to <tt>Encoding::UTF_8</tt>;
7125 * on Windows, enables conversion between EOL and CRLF
7126 * and enables interpreting <tt>0x1A</tt> as an end-of-file marker.
7127 * - <tt>'b'</tt>: Binary data; sets the default external encoding
7128 * to <tt>Encoding::ASCII_8BIT</tt>;
7129 * on Windows, suppresses conversion between EOL and CRLF
7130 * and disables interpreting <tt>0x1A</tt> as an end-of-file marker.
7132 * If neither is given, the stream defaults to text data.
7134 * Examples:
7136 * File.new('t.txt', 'rt')
7137 * File.new('t.dat', 'rb')
7139 * When the data mode is specified, the read/write mode may not be omitted,
7140 * and the data mode must precede the file-create mode, if given:
7142 * File.new('t.dat', 'b') # Raises an exception.
7143 * File.new('t.dat', 'rxb') # Raises an exception.
7145 * ==== \File-Create Mode
7147 * The following may be suffixed to any writable string mode above:
7149 * - <tt>'x'</tt>: Creates the file if it does not exist;
7150 * raises an exception if the file exists.
7152 * Example:
7154 * File.new('t.tmp', 'wx')
7156 * When the file-create mode is specified, the read/write mode may not be omitted,
7157 * and the file-create mode must follow the data mode:
7159 * File.new('t.dat', 'x') # Raises an exception.
7160 * File.new('t.dat', 'rxb') # Raises an exception.
7162 * === \Integer Access Modes
7164 * When mode is an integer it must be one or more of the following constants,
7165 * which may be combined by the bitwise OR operator <tt>|</tt>:
7167 * - +File::RDONLY+: Open for reading only.
7168 * - +File::WRONLY+: Open for writing only.
7169 * - +File::RDWR+: Open for reading and writing.
7170 * - +File::APPEND+: Open for appending only.
7172 * Examples:
7174 * File.new('t.txt', File::RDONLY)
7175 * File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
7177 * Note: Method IO#set_encoding does not allow the mode to be specified as an integer.
7179 * === File-Create Mode Specified as an \Integer
7181 * These constants may also be ORed into the integer mode:
7183 * - +File::CREAT+: Create file if it does not exist.
7184 * - +File::EXCL+: Raise an exception if +File::CREAT+ is given and the file exists.
7186 * === \Data Mode Specified as an \Integer
7188 * \Data mode cannot be specified as an integer.
7189 * When the stream access mode is given as an integer,
7190 * the data mode is always text, never binary.
7192 * Note that although there is a constant +File::BINARY+,
7193 * setting its value in an integer stream mode has no effect;
7194 * this is because, as documented in File::Constants,
7195 * the +File::BINARY+ value disables line code conversion,
7196 * but does not change the external encoding.
7198 * === Encodings
7200 * Any of the string modes above may specify encodings -
7201 * either external encoding only or both external and internal encodings -
7202 * by appending one or both encoding names, separated by colons:
7204 * f = File.new('t.dat', 'rb')
7205 * f.external_encoding # => #<Encoding:ASCII-8BIT>
7206 * f.internal_encoding # => nil
7207 * f = File.new('t.dat', 'rb:UTF-16')
7208 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
7209 * f.internal_encoding # => nil
7210 * f = File.new('t.dat', 'rb:UTF-16:UTF-16')
7211 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
7212 * f.internal_encoding # => #<Encoding:UTF-16>
7213 * f.close
7215 * The numerous encoding names are available in array Encoding.name_list:
7217 * Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
7219 * When the external encoding is set, strings read are tagged by that encoding
7220 * when reading, and strings written are converted to that encoding when
7221 * writing.
7223 * When both external and internal encodings are set,
7224 * strings read are converted from external to internal encoding,
7225 * and strings written are converted from internal to external encoding.
7226 * For further details about transcoding input and output,
7227 * see {Encodings}[rdoc-ref:encodings.rdoc@Encodings].
7229 * If the external encoding is <tt>'BOM|UTF-8'</tt>, <tt>'BOM|UTF-16LE'</tt>
7230 * or <tt>'BOM|UTF16-BE'</tt>,
7231 * Ruby checks for a Unicode BOM in the input document
7232 * to help determine the encoding.
7233 * For UTF-16 encodings the file open mode must be binary.
7234 * If the BOM is found,
7235 * it is stripped and the external encoding from the BOM is used.
7237 * Note that the BOM-style encoding option is case insensitive,
7238 * so <tt>'bom|utf-8'</tt> is also valid.
7240 * == \File Permissions
7242 * A \File object has _permissions_, an octal integer representing
7243 * the permissions of an actual file in the underlying platform.
7245 * Note that file permissions are quite different from the _mode_
7246 * of a file stream (\File object).
7248 * In a \File object, the permissions are available thus,
7249 * where method +mode+, despite its name, returns permissions:
7251 * f = File.new('t.txt')
7252 * f.lstat.mode.to_s(8) # => "100644"
7254 * On a Unix-based operating system,
7255 * the three low-order octal digits represent the permissions
7256 * for owner (6), group (4), and world (4).
7257 * The triplet of bits in each octal digit represent, respectively,
7258 * read, write, and execute permissions.
7260 * Permissions <tt>0644</tt> thus represent read-write access for owner
7261 * and read-only access for group and world.
7262 * See man pages {open(2)}[https://www.unix.com/man-page/bsd/2/open]
7263 * and {chmod(2)}[https://www.unix.com/man-page/bsd/2/chmod].
7265 * For a directory, the meaning of the execute bit changes:
7266 * when set, the directory can be searched.
7268 * Higher-order bits in permissions may indicate the type of file
7269 * (plain, directory, pipe, socket, etc.) and various other special features.
7271 * On non-Posix operating systems, permissions may include only read-only or read-write,
7272 * in which case, the remaining permission will resemble typical values.
7273 * On Windows, for instance, the default permissions are <code>0644</code>;
7274 * The only change that can be made is to make the file
7275 * read-only, which is reported as <code>0444</code>.
7277 * For a method that actually creates a file in the underlying platform
7278 * (as opposed to merely creating a \File object),
7279 * permissions may be specified:
7281 * File.new('t.tmp', File::CREAT, 0644)
7282 * File.new('t.tmp', File::CREAT, 0444)
7284 * Permissions may also be changed:
7286 * f = File.new('t.tmp', File::CREAT, 0444)
7287 * f.chmod(0644)
7288 * f.chmod(0444)
7290 * == \File \Constants
7292 * Various constants for use in \File and IO methods
7293 * may be found in module File::Constants;
7294 * an array of their names is returned by <tt>File::Constants.constants</tt>.
7296 * == What's Here
7298 * First, what's elsewhere. \Class \File:
7300 * - Inherits from {class IO}[rdoc-ref:IO@What-27s+Here],
7301 * in particular, methods for creating, reading, and writing files
7302 * - Includes module FileTest,
7303 * which provides dozens of additional methods.
7305 * Here, class \File provides methods that are useful for:
7307 * - {Creating}[rdoc-ref:File@Creating]
7308 * - {Querying}[rdoc-ref:File@Querying]
7309 * - {Settings}[rdoc-ref:File@Settings]
7310 * - {Other}[rdoc-ref:File@Other]
7312 * === Creating
7314 * - ::new: Opens the file at the given path; returns the file.
7315 * - ::open: Same as ::new, but when given a block will yield the file to the block,
7316 * and close the file upon exiting the block.
7317 * - ::link: Creates a new name for an existing file using a hard link.
7318 * - ::mkfifo: Returns the FIFO file created at the given path.
7319 * - ::symlink: Creates a symbolic link for the given file path.
7321 * === Querying
7323 * _Paths_
7325 * - ::absolute_path: Returns the absolute file path for the given path.
7326 * - ::absolute_path?: Returns whether the given path is the absolute file path.
7327 * - ::basename: Returns the last component of the given file path.
7328 * - ::dirname: Returns all but the last component of the given file path.
7329 * - ::expand_path: Returns the absolute file path for the given path,
7330 * expanding <tt>~</tt> for a home directory.
7331 * - ::extname: Returns the file extension for the given file path.
7332 * - ::fnmatch? (aliased as ::fnmatch): Returns whether the given file path
7333 * matches the given pattern.
7334 * - ::join: Joins path components into a single path string.
7335 * - ::path: Returns the string representation of the given path.
7336 * - ::readlink: Returns the path to the file at the given symbolic link.
7337 * - ::realdirpath: Returns the real path for the given file path,
7338 * where the last component need not exist.
7339 * - ::realpath: Returns the real path for the given file path,
7340 * where all components must exist.
7341 * - ::split: Returns an array of two strings: the directory name and basename
7342 * of the file at the given path.
7343 * - #path (aliased as #to_path): Returns the string representation of the given path.
7345 * _Times_
7347 * - ::atime: Returns a Time for the most recent access to the given file.
7348 * - ::birthtime: Returns a Time for the creation of the given file.
7349 * - ::ctime: Returns a Time for the metadata change of the given file.
7350 * - ::mtime: Returns a Time for the most recent data modification to
7351 * the content of the given file.
7352 * - #atime: Returns a Time for the most recent access to +self+.
7353 * - #birthtime: Returns a Time the creation for +self+.
7354 * - #ctime: Returns a Time for the metadata change of +self+.
7355 * - #mtime: Returns a Time for the most recent data modification
7356 * to the content of +self+.
7358 * _Types_
7360 * - ::blockdev?: Returns whether the file at the given path is a block device.
7361 * - ::chardev?: Returns whether the file at the given path is a character device.
7362 * - ::directory?: Returns whether the file at the given path is a directory.
7363 * - ::executable?: Returns whether the file at the given path is executable
7364 * by the effective user and group of the current process.
7365 * - ::executable_real?: Returns whether the file at the given path is executable
7366 * by the real user and group of the current process.
7367 * - ::exist?: Returns whether the file at the given path exists.
7368 * - ::file?: Returns whether the file at the given path is a regular file.
7369 * - ::ftype: Returns a string giving the type of the file at the given path.
7370 * - ::grpowned?: Returns whether the effective group of the current process
7371 * owns the file at the given path.
7372 * - ::identical?: Returns whether the files at two given paths are identical.
7373 * - ::lstat: Returns the File::Stat object for the last symbolic link
7374 * in the given path.
7375 * - ::owned?: Returns whether the effective user of the current process
7376 * owns the file at the given path.
7377 * - ::pipe?: Returns whether the file at the given path is a pipe.
7378 * - ::readable?: Returns whether the file at the given path is readable
7379 * by the effective user and group of the current process.
7380 * - ::readable_real?: Returns whether the file at the given path is readable
7381 * by the real user and group of the current process.
7382 * - ::setgid?: Returns whether the setgid bit is set for the file at the given path.
7383 * - ::setuid?: Returns whether the setuid bit is set for the file at the given path.
7384 * - ::socket?: Returns whether the file at the given path is a socket.
7385 * - ::stat: Returns the File::Stat object for the file at the given path.
7386 * - ::sticky?: Returns whether the file at the given path has its sticky bit set.
7387 * - ::symlink?: Returns whether the file at the given path is a symbolic link.
7388 * - ::umask: Returns the umask value for the current process.
7389 * - ::world_readable?: Returns whether the file at the given path is readable
7390 * by others.
7391 * - ::world_writable?: Returns whether the file at the given path is writable
7392 * by others.
7393 * - ::writable?: Returns whether the file at the given path is writable
7394 * by the effective user and group of the current process.
7395 * - ::writable_real?: Returns whether the file at the given path is writable
7396 * by the real user and group of the current process.
7397 * - #lstat: Returns the File::Stat object for the last symbolic link
7398 * in the path for +self+.
7400 * _Contents_
7402 * - ::empty? (aliased as ::zero?): Returns whether the file at the given path
7403 * exists and is empty.
7404 * - ::size: Returns the size (bytes) of the file at the given path.
7405 * - ::size?: Returns +nil+ if there is no file at the given path,
7406 * or if that file is empty; otherwise returns the file size (bytes).
7407 * - #size: Returns the size (bytes) of +self+.
7409 * === Settings
7411 * - ::chmod: Changes permissions of the file at the given path.
7412 * - ::chown: Change ownership of the file at the given path.
7413 * - ::lchmod: Changes permissions of the last symbolic link in the given path.
7414 * - ::lchown: Change ownership of the last symbolic in the given path.
7415 * - ::lutime: For each given file path, sets the access time and modification time
7416 * of the last symbolic link in the path.
7417 * - ::rename: Moves the file at one given path to another given path.
7418 * - ::utime: Sets the access time and modification time of each file
7419 * at the given paths.
7420 * - #flock: Locks or unlocks +self+.
7422 * === Other
7424 * - ::truncate: Truncates the file at the given file path to the given size.
7425 * - ::unlink (aliased as ::delete): Deletes the file for each given file path.
7426 * - #truncate: Truncates +self+ to the given size.
7430 void
7431 Init_File(void)
7433 #if defined(__APPLE__) && defined(HAVE_WORKING_FORK)
7434 rb_CFString_class_initialize_before_fork();
7435 #endif
7437 VALUE separator;
7439 rb_mFileTest = rb_define_module("FileTest");
7440 rb_cFile = rb_define_class("File", rb_cIO);
7442 define_filetest_function("directory?", rb_file_directory_p, 1);
7443 define_filetest_function("exist?", rb_file_exist_p, 1);
7444 define_filetest_function("readable?", rb_file_readable_p, 1);
7445 define_filetest_function("readable_real?", rb_file_readable_real_p, 1);
7446 define_filetest_function("world_readable?", rb_file_world_readable_p, 1);
7447 define_filetest_function("writable?", rb_file_writable_p, 1);
7448 define_filetest_function("writable_real?", rb_file_writable_real_p, 1);
7449 define_filetest_function("world_writable?", rb_file_world_writable_p, 1);
7450 define_filetest_function("executable?", rb_file_executable_p, 1);
7451 define_filetest_function("executable_real?", rb_file_executable_real_p, 1);
7452 define_filetest_function("file?", rb_file_file_p, 1);
7453 define_filetest_function("zero?", rb_file_zero_p, 1);
7454 define_filetest_function("empty?", rb_file_zero_p, 1);
7455 define_filetest_function("size?", rb_file_size_p, 1);
7456 define_filetest_function("size", rb_file_s_size, 1);
7457 define_filetest_function("owned?", rb_file_owned_p, 1);
7458 define_filetest_function("grpowned?", rb_file_grpowned_p, 1);
7460 define_filetest_function("pipe?", rb_file_pipe_p, 1);
7461 define_filetest_function("symlink?", rb_file_symlink_p, 1);
7462 define_filetest_function("socket?", rb_file_socket_p, 1);
7464 define_filetest_function("blockdev?", rb_file_blockdev_p, 1);
7465 define_filetest_function("chardev?", rb_file_chardev_p, 1);
7467 define_filetest_function("setuid?", rb_file_suid_p, 1);
7468 define_filetest_function("setgid?", rb_file_sgid_p, 1);
7469 define_filetest_function("sticky?", rb_file_sticky_p, 1);
7471 define_filetest_function("identical?", rb_file_identical_p, 2);
7473 rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
7474 rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
7475 rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
7477 rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
7478 rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
7479 rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
7480 rb_define_singleton_method(rb_cFile, "birthtime", rb_file_s_birthtime, 1);
7482 rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
7483 rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
7484 rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
7485 rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
7486 rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
7487 rb_define_singleton_method(rb_cFile, "lutime", rb_file_s_lutime, -1);
7489 rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
7490 rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
7491 rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
7493 rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -1);
7494 rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -1);
7495 rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
7496 rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
7497 rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
7498 rb_define_singleton_method(rb_cFile, "mkfifo", rb_file_s_mkfifo, -1);
7499 rb_define_singleton_method(rb_cFile, "expand_path", s_expand_path, -1);
7500 rb_define_singleton_method(rb_cFile, "absolute_path", s_absolute_path, -1);
7501 rb_define_singleton_method(rb_cFile, "absolute_path?", s_absolute_path_p, 1);
7502 rb_define_singleton_method(rb_cFile, "realpath", rb_file_s_realpath, -1);
7503 rb_define_singleton_method(rb_cFile, "realdirpath", rb_file_s_realdirpath, -1);
7504 rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
7505 rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, -1);
7506 rb_define_singleton_method(rb_cFile, "extname", rb_file_s_extname, 1);
7507 rb_define_singleton_method(rb_cFile, "path", rb_file_s_path, 1);
7509 separator = rb_fstring_lit("/");
7510 /* separates directory parts in path */
7511 rb_define_const(rb_cFile, "Separator", separator);
7512 /* separates directory parts in path */
7513 rb_define_const(rb_cFile, "SEPARATOR", separator);
7514 rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
7515 rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -2);
7517 #ifdef DOSISH
7518 /* platform specific alternative separator */
7519 rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator)));
7520 #else
7521 rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
7522 #endif
7523 /* path list separator */
7524 rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP));
7526 rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
7527 rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
7529 rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
7530 rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
7531 rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
7532 rb_define_method(rb_cFile, "birthtime", rb_file_birthtime, 0);
7533 rb_define_method(rb_cFile, "size", file_size, 0);
7535 rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
7536 rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
7537 rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
7539 rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
7542 * Document-module: File::Constants
7544 * \Module +File::Constants+ defines file-related constants.
7546 * There are two families of constants here:
7548 * - Those having to do with {file access}[rdoc-ref:File::Constants@File+Access].
7549 * - Those having to do with {filename globbing}[rdoc-ref:File::Constants@Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29].
7551 * \File constants defined for the local process may be retrieved
7552 * with method File::Constants.constants:
7554 * File::Constants.constants.take(5)
7555 * # => [:RDONLY, :WRONLY, :RDWR, :APPEND, :CREAT]
7557 * == \File Access
7559 * \File-access constants may be used with optional argument +mode+ in calls
7560 * to the following methods:
7562 * - File.new.
7563 * - File.open.
7564 * - IO.for_fd.
7565 * - IO.new.
7566 * - IO.open.
7567 * - IO.popen.
7568 * - IO.reopen.
7569 * - IO.sysopen.
7570 * - StringIO.new.
7571 * - StringIO.open.
7572 * - StringIO#reopen.
7574 * === Read/Write Access
7576 * Read-write access for a stream
7577 * may be specified by a file-access constant.
7579 * The constant may be specified as part of a bitwise OR of other such constants.
7581 * Any combination of the constants in this section may be specified.
7583 * ==== File::RDONLY
7585 * Flag File::RDONLY specifies the stream should be opened for reading only:
7587 * filepath = '/tmp/t.tmp'
7588 * f = File.new(filepath, File::RDONLY)
7589 * f.write('Foo') # Raises IOError (not opened for writing).
7591 * ==== File::WRONLY
7593 * Flag File::WRONLY specifies that the stream should be opened for writing only:
7595 * f = File.new(filepath, File::WRONLY)
7596 * f.read # Raises IOError (not opened for reading).
7598 * ==== File::RDWR
7600 * Flag File::RDWR specifies that the stream should be opened
7601 * for both reading and writing:
7603 * f = File.new(filepath, File::RDWR)
7604 * f.write('Foo') # => 3
7605 * f.rewind # => 0
7606 * f.read # => "Foo"
7608 * === \File Positioning
7610 * ==== File::APPEND
7612 * Flag File::APPEND specifies that the stream should be opened
7613 * in append mode.
7615 * Before each write operation, the position is set to end-of-stream.
7616 * The modification of the position and the following write operation
7617 * are performed as a single atomic step.
7619 * ==== File::TRUNC
7621 * Flag File::TRUNC specifies that the stream should be truncated
7622 * at its beginning.
7623 * If the file exists and is successfully opened for writing,
7624 * it is to be truncated to position zero;
7625 * its ctime and mtime are updated.
7627 * There is no effect on a FIFO special file or a terminal device.
7628 * The effect on other file types is implementation-defined.
7629 * The result of using File::TRUNC with File::RDONLY is undefined.
7631 * === Creating and Preserving
7633 * ==== File::CREAT
7635 * Flag File::CREAT specifies that the stream should be created
7636 * if it does not already exist.
7638 * If the file exists:
7640 * - Raise an exception if File::EXCL is also specified.
7641 * - Otherwise, do nothing.
7643 * If the file does not exist, then it is created.
7644 * Upon successful completion, the atime, ctime, and mtime of the file are updated,
7645 * and the ctime and mtime of the parent directory are updated.
7647 * ==== File::EXCL
7649 * Flag File::EXCL specifies that the stream should not already exist;
7650 * If flags File::CREAT and File::EXCL are both specified
7651 * and the stream already exists, an exception is raised.
7653 * The check for the existence and creation of the file is performed as an
7654 * atomic operation.
7656 * If both File::EXCL and File::CREAT are specified and the path names a symbolic link,
7657 * an exception is raised regardless of the contents of the symbolic link.
7659 * If File::EXCL is specified and File::CREAT is not specified,
7660 * the result is undefined.
7662 * === POSIX \File \Constants
7664 * Some file-access constants are defined only on POSIX-compliant systems;
7665 * those are:
7667 * - File::SYNC.
7668 * - File::DSYNC.
7669 * - File::RSYNC.
7670 * - File::DIRECT.
7671 * - File::NOATIME.
7672 * - File::NOCTTY.
7673 * - File::NOFOLLOW.
7674 * - File::TMPFILE.
7676 * ==== File::SYNC, File::RSYNC, and File::DSYNC
7678 * Flag File::SYNC, File::RSYNC, or File::DSYNC
7679 * specifies synchronization of I/O operations with the underlying file system.
7681 * These flags are valid only for POSIX-compliant systems.
7683 * - File::SYNC specifies that all write operations (both data and metadata)
7684 * are immediately to be flushed to the underlying storage device.
7685 * This means that the data is written to the storage device,
7686 * and the file's metadata (e.g., file size, timestamps, permissions)
7687 * are also synchronized.
7688 * This guarantees that data is safely stored on the storage medium
7689 * before returning control to the calling program.
7690 * This flag can have a significant impact on performance
7691 * since it requires synchronous writes, which can be slower
7692 * compared to asynchronous writes.
7694 * - File::RSYNC specifies that any read operations on the file will not return
7695 * until all outstanding write operations
7696 * (those that have been issued but not completed) are also synchronized.
7697 * This is useful when you want to read the most up-to-date data,
7698 * which may still be in the process of being written.
7700 * - File::DSYNC specifies that all _data_ write operations
7701 * are immediately to be flushed to the underlying storage device;
7702 * this differs from File::SYNC, which requires that _metadata_
7703 * also be synchronized.
7705 * Note that the behavior of these flags may vary slightly
7706 * depending on the operating system and filesystem being used.
7707 * Additionally, using these flags can have an impact on performance
7708 * due to the synchronous nature of the I/O operations,
7709 * so they should be used judiciously,
7710 * especially in performance-critical applications.
7712 * ==== File::NOCTTY
7714 * Flag File::NOCTTY specifies that if the stream is a terminal device,
7715 * that device does not become the controlling terminal for the process.
7717 * Defined only for POSIX-compliant systems.
7719 * ==== File::DIRECT
7721 * Flag File::DIRECT requests that cache effects of the I/O to and from the stream
7722 * be minimized.
7724 * Defined only for POSIX-compliant systems.
7726 * ==== File::NOATIME
7728 * Flag File::NOATIME specifies that act of opening the stream
7729 * should not modify its access time (atime).
7731 * Defined only for POSIX-compliant systems.
7733 * ==== File::NOFOLLOW
7735 * Flag File::NOFOLLOW specifies that if path is a symbolic link,
7736 * it should not be followed.
7738 * Defined only for POSIX-compliant systems.
7740 * ==== File::TMPFILE
7742 * Flag File::TMPFILE specifies that the opened stream
7743 * should be a new temporary file.
7745 * Defined only for POSIX-compliant systems.
7747 * === Other File-Access \Constants
7749 * ==== File::NONBLOCK
7751 * When possible, the file is opened in nonblocking mode.
7752 * Neither the open operation nor any subsequent I/O operations on
7753 * the file will cause the calling process to wait.
7755 * ==== File::BINARY
7757 * Flag File::BINARY specifies that the stream is to be accessed in binary mode.
7759 * ==== File::SHARE_DELETE
7761 * Flag File::SHARE_DELETE enables other processes to open the stream
7762 * with delete access.
7764 * Windows only.
7766 * If the stream is opened for (local) delete access without File::SHARE_DELETE,
7767 * and another process attempts to open it with delete access,
7768 * the attempt fails and the stream is not opened for that process.
7770 * == Locking
7772 * Four file constants relate to stream locking;
7773 * see File#flock:
7775 * ==== File::LOCK_EX
7777 * Flag File::LOCK_EX specifies an exclusive lock;
7778 * only one process a a time may lock the stream.
7780 * ==== File::LOCK_NB
7782 * Flag File::LOCK_NB specifies non-blocking locking for the stream;
7783 * may be combined with File::LOCK_EX or File::LOCK_SH.
7785 * ==== File::LOCK_SH
7787 * Flag File::LOCK_SH specifies that multiple processes may lock
7788 * the stream at the same time.
7790 * ==== File::LOCK_UN
7792 * Flag File::LOCK_UN specifies that the stream is not to be locked.
7794 * == Filename Globbing \Constants (File::FNM_*)
7796 * Filename-globbing constants may be used with optional argument +flags+
7797 * in calls to the following methods:
7799 * - Dir.glob.
7800 * - File.fnmatch.
7801 * - Pathname#fnmatch.
7802 * - Pathname.glob.
7803 * - Pathname#glob.
7805 * The constants are:
7807 * ==== File::FNM_CASEFOLD
7809 * Flag File::FNM_CASEFOLD makes patterns case insensitive
7810 * for File.fnmatch (but not Dir.glob).
7812 * ==== File::FNM_DOTMATCH
7814 * Flag File::FNM_DOTMATCH makes the <tt>'*'</tt> pattern
7815 * match a filename starting with <tt>'.'</tt>.
7817 * ==== File::FNM_EXTGLOB
7819 * Flag File::FNM_EXTGLOB enables pattern <tt>'{_a_,_b_}'</tt>,
7820 * which matches pattern '_a_' and pattern '_b_';
7821 * behaves like
7822 * a {regexp union}[rdoc-ref:Regexp.union]
7823 * (e.g., <tt>'(?:_a_|_b_)'</tt>):
7825 * pattern = '{LEGAL,BSDL}'
7826 * Dir.glob(pattern) # => ["LEGAL", "BSDL"]
7827 * Pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
7828 * pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
7830 * ==== File::FNM_NOESCAPE
7832 * Flag File::FNM_NOESCAPE disables <tt>'\'</tt> escaping.
7834 * ==== File::FNM_PATHNAME
7836 * Flag File::FNM_PATHNAME specifies that patterns <tt>'*'</tt> and <tt>'?'</tt>
7837 * do not match the directory separator
7838 * (the value of constant File::SEPARATOR).
7840 * ==== File::FNM_SHORTNAME
7842 * Flag File::FNM_SHORTNAME allows patterns to match short names if they exist.
7844 * Windows only.
7846 * ==== File::FNM_SYSCASE
7848 * Flag File::FNM_SYSCASE specifies that case sensitivity
7849 * is the same as in the underlying operating system;
7850 * effective for File.fnmatch, but not Dir.glob.
7852 * == Other \Constants
7854 * ==== File::NULL
7856 * Flag File::NULL contains the string value of the null device:
7858 * - On a Unix-like OS, <tt>'/dev/null'</tt>.
7859 * - On Windows, <tt>'NUL'</tt>.
7862 rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
7863 rb_include_module(rb_cIO, rb_mFConst);
7864 /* {File::RDONLY}[rdoc-ref:File::Constants@File-3A-3ARDONLY] */
7865 rb_define_const(rb_mFConst, "RDONLY", INT2FIX(O_RDONLY));
7866 /* {File::WRONLY}[rdoc-ref:File::Constants@File-3A-3AWRONLY] */
7867 rb_define_const(rb_mFConst, "WRONLY", INT2FIX(O_WRONLY));
7868 /* {File::RDWR}[rdoc-ref:File::Constants@File-3A-3ARDWR] */
7869 rb_define_const(rb_mFConst, "RDWR", INT2FIX(O_RDWR));
7870 /* {File::APPEND}[rdoc-ref:File::Constants@File-3A-3AAPPEND] */
7871 rb_define_const(rb_mFConst, "APPEND", INT2FIX(O_APPEND));
7872 /* {File::CREAT}[rdoc-ref:File::Constants@File-3A-3ACREAT] */
7873 rb_define_const(rb_mFConst, "CREAT", INT2FIX(O_CREAT));
7874 /* {File::EXCL}[rdoc-ref:File::Constants@File-3A-3AEXCL] */
7875 rb_define_const(rb_mFConst, "EXCL", INT2FIX(O_EXCL));
7876 #if defined(O_NDELAY) || defined(O_NONBLOCK)
7877 # ifndef O_NONBLOCK
7878 # define O_NONBLOCK O_NDELAY
7879 # endif
7880 /* {File::NONBLOCK}[rdoc-ref:File::Constants@File-3A-3ANONBLOCK] */
7881 rb_define_const(rb_mFConst, "NONBLOCK", INT2FIX(O_NONBLOCK));
7882 #endif
7883 /* {File::TRUNC}[rdoc-ref:File::Constants@File-3A-3ATRUNC] */
7884 rb_define_const(rb_mFConst, "TRUNC", INT2FIX(O_TRUNC));
7885 #ifdef O_NOCTTY
7886 /* {File::NOCTTY}[rdoc-ref:File::Constants@File-3A-3ANOCTTY] */
7887 rb_define_const(rb_mFConst, "NOCTTY", INT2FIX(O_NOCTTY));
7888 #endif
7889 #ifndef O_BINARY
7890 # define O_BINARY 0
7891 #endif
7892 /* {File::BINARY}[rdoc-ref:File::Constants@File-3A-3ABINARY] */
7893 rb_define_const(rb_mFConst, "BINARY", INT2FIX(O_BINARY));
7894 #ifndef O_SHARE_DELETE
7895 # define O_SHARE_DELETE 0
7896 #endif
7897 /* {File::SHARE_DELETE}[rdoc-ref:File::Constants@File-3A-3ASHARE_DELETE] */
7898 rb_define_const(rb_mFConst, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE));
7899 #ifdef O_SYNC
7900 /* {File::SYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7901 rb_define_const(rb_mFConst, "SYNC", INT2FIX(O_SYNC));
7902 #endif
7903 #ifdef O_DSYNC
7904 /* {File::DSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7905 rb_define_const(rb_mFConst, "DSYNC", INT2FIX(O_DSYNC));
7906 #endif
7907 #ifdef O_RSYNC
7908 /* {File::RSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7909 rb_define_const(rb_mFConst, "RSYNC", INT2FIX(O_RSYNC));
7910 #endif
7911 #ifdef O_NOFOLLOW
7912 /* {File::NOFOLLOW}[rdoc-ref:File::Constants@File-3A-3ANOFOLLOW] */
7913 rb_define_const(rb_mFConst, "NOFOLLOW", INT2FIX(O_NOFOLLOW)); /* FreeBSD, Linux */
7914 #endif
7915 #ifdef O_NOATIME
7916 /* {File::NOATIME}[rdoc-ref:File::Constants@File-3A-3ANOATIME] */
7917 rb_define_const(rb_mFConst, "NOATIME", INT2FIX(O_NOATIME)); /* Linux */
7918 #endif
7919 #ifdef O_DIRECT
7920 /* {File::DIRECT}[rdoc-ref:File::Constants@File-3A-3ADIRECT] */
7921 rb_define_const(rb_mFConst, "DIRECT", INT2FIX(O_DIRECT));
7922 #endif
7923 #ifdef O_TMPFILE
7924 /* {File::TMPFILE}[rdoc-ref:File::Constants@File-3A-3ATMPFILE] */
7925 rb_define_const(rb_mFConst, "TMPFILE", INT2FIX(O_TMPFILE));
7926 #endif
7928 /* {File::LOCK_SH}[rdoc-ref:File::Constants@File-3A-3ALOCK_SH] */
7929 rb_define_const(rb_mFConst, "LOCK_SH", INT2FIX(LOCK_SH));
7930 /* {File::LOCK_EX}[rdoc-ref:File::Constants@File-3A-3ALOCK_EX] */
7931 rb_define_const(rb_mFConst, "LOCK_EX", INT2FIX(LOCK_EX));
7932 /* {File::LOCK_UN}[rdoc-ref:File::Constants@File-3A-3ALOCK_UN] */
7933 rb_define_const(rb_mFConst, "LOCK_UN", INT2FIX(LOCK_UN));
7934 /* {File::LOCK_NB}[rdoc-ref:File::Constants@File-3A-3ALOCK_NB] */
7935 rb_define_const(rb_mFConst, "LOCK_NB", INT2FIX(LOCK_NB));
7937 /* {File::NULL}[rdoc-ref:File::Constants@File-3A-3ANULL] */
7938 rb_define_const(rb_mFConst, "NULL", rb_fstring_cstr(ruby_null_device));
7940 rb_define_global_function("test", rb_f_test, -1);
7942 rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
7943 rb_define_alloc_func(rb_cStat, rb_stat_s_alloc);
7944 rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
7945 rb_define_method(rb_cStat, "initialize_copy", rb_stat_init_copy, 1);
7947 rb_include_module(rb_cStat, rb_mComparable);
7949 rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
7951 rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
7952 rb_define_method(rb_cStat, "dev_major", rb_stat_dev_major, 0);
7953 rb_define_method(rb_cStat, "dev_minor", rb_stat_dev_minor, 0);
7954 rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
7955 rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
7956 rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
7957 rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
7958 rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
7959 rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
7960 rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
7961 rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
7962 rb_define_method(rb_cStat, "size", rb_stat_size, 0);
7963 rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
7964 rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
7965 rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
7966 rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
7967 rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
7968 rb_define_method(rb_cStat, "birthtime", rb_stat_birthtime, 0);
7970 rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
7972 rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
7974 rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
7975 rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
7976 rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
7977 rb_define_method(rb_cStat, "world_readable?", rb_stat_wr, 0);
7978 rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
7979 rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
7980 rb_define_method(rb_cStat, "world_writable?", rb_stat_ww, 0);
7981 rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
7982 rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
7983 rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
7984 rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
7985 rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
7986 rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
7987 rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
7989 rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
7990 rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
7991 rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
7993 rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
7994 rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
7996 rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
7997 rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
7998 rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);