1 /**********************************************************************
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"
17 # include "missing/file.h"
26 # include <sys/cygwin.h>
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(...)
39 # include <CoreFoundation/CFString.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
50 #ifdef HAVE_SYS_FILE_H
51 # include <sys/file.h>
56 #ifdef HAVE_SYS_PARAM_H
57 # include <sys/param.h>
60 # define MAXPATHLEN 1024
65 #elif defined HAVE_SYS_UTIME_H
66 # include <sys/utime.h>
73 #ifdef HAVE_SYS_SYSMACROS_H
74 # include <sys/sysmacros.h>
77 #include <sys/types.h>
80 #ifdef HAVE_SYS_MKDEV_H
81 # include <sys/mkdev.h>
84 #if defined(HAVE_FCNTL_H)
88 #if defined(HAVE_SYS_TIME_H)
89 # include <sys/time.h>
92 #if !defined HAVE_LSTAT && !defined lstat
96 /* define system APIs */
98 # include "win32/file.h"
99 # define STAT(p, s) rb_w32_ustati128((p), (s))
101 # define lstat(p, s) rb_w32_ulstati128((p), (s))
103 # define access(p, m) rb_w32_uaccess((p), (m))
105 # define truncate(p, n) rb_w32_utruncate((p), (n))
107 # define chmod(p, m) rb_w32_uchmod((p), (m))
109 # define chown(p, o, g) rb_w32_uchown((p), (o), (g))
111 # define lchown(p, o, g) rb_w32_ulchown((p), (o), (g))
113 # define utimensat(s, p, t, f) rb_w32_uutimensat((s), (p), (t), (f))
115 # define link(f, t) rb_w32_ulink((f), (t))
117 # define unlink(p) rb_w32_uunlink(p)
119 # define readlink(f, t, l) rb_w32_ureadlink((f), (t), (l))
121 # define rename(f, t) rb_w32_urename((f), (t))
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
131 # define STAT(p, s) stat((p), (s))
134 #if defined _WIN32 || defined __APPLE__
135 # define USE_OSPATH 1
136 # define TO_OSPATH(str) rb_str_encode_ospath(str)
138 # define USE_OSPATH 0
139 # define TO_OSPATH(str) (str)
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
147 /* Solaris 10 realpath(3) doesn't support File.realpath */
148 #if defined HAVE_REALPATH && defined __sun && defined __SVR4
158 #include "encindex.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"
180 file_path_convert(VALUE name
)
182 #ifndef _WIN32 /* non Windows == Unix */
183 int fname_encidx
= ENCODING_GET(name
);
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
);
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
));
212 rb_get_path_check_to_string(VALUE obj
)
217 if (RB_TYPE_P(obj
, T_STRING
)) {
220 CONST_ID(to_path
, "to_path");
221 tmp
= rb_check_funcall_default(obj
, to_path
, 0, 0, obj
);
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
);
240 rb_get_path_no_checksafe(VALUE obj
)
242 return rb_get_path(obj
);
246 rb_get_path(VALUE obj
)
248 return rb_get_path_check_convert(rb_get_path_check_to_string(obj
));
252 rb_str_encode_ospath(VALUE path
)
255 int encidx
= ENCODING_GET(path
);
256 #if 0 && defined _WIN32
257 if (encidx
== ENCINDEX_ASCII_8BIT
) {
258 encidx
= rb_filesystem_encindex();
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 */
271 # define NORMALIZE_UTF8PATH 1
273 # ifdef HAVE_WORKING_FORK
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
);
310 # endif /* HAVE_WORKING_FORK */
313 rb_str_append_normalized_ospath(VALUE str
, const char *ptr
, long len
)
317 CFStringRef s
= CFStringCreateWithBytesNoCopy(kCFAllocatorDefault
,
318 (const UInt8
*)ptr
, len
,
319 kCFStringEncodingUTF8
, FALSE
,
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
);
337 rb_str_normalize_ospath(const char *ptr
, long len
)
340 const char *e
= ptr
+ len
;
342 VALUE str
= rb_str_buf_new(len
);
343 rb_encoding
*enc
= rb_utf8_encoding();
344 rb_enc_associate(str
, enc
);
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
));
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)) {
363 rb_str_append_normalized_ospath(str
, p1
, p
-p1
);
365 rb_str_cat(str
, p
, l
);
374 rb_str_append_normalized_ospath(str
, p1
, p
-p1
);
381 ignored_char_p(const char *p
, const char *e
, rb_encoding
*enc
)
384 if (p
+3 > e
) return 0;
385 switch ((unsigned char)*p
) {
387 switch ((unsigned char)p
[1]) {
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;
396 c
= (unsigned char)p
[2];
397 /* c >= 0x206a && c <= 0x206f */
398 if (c
>= 0xaa && c
<= 0xaf) return 3;
404 if ((unsigned char)p
[1] == 0xbb &&
405 (unsigned char)p
[2] == 0xbf)
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
{
426 int (*func
)(const char *, void *);
428 struct apply_filename fn
[FLEX_ARY_LEN
];
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) {
446 NORETURN(static void utime_failed(struct apply_arg
*));
447 static int utime_internal(const char *, void *);
451 apply2files(int (*func
)(const char *, void *), int argc
, VALUE
*argv
, void *arg
)
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
);
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
);
474 if (func
== utime_internal
) {
478 rb_syserr_fail_path(aa
->errnum
, aa
->fn
[aa
->i
].path
);
483 return LONG2FIX(argc
);
486 static const rb_data_type_t stat_data_type
= {
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
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
);
508 rb_st
->initialized
= true;
514 rb_stat_new(const struct stat
*st
)
516 return stat_new_0(rb_cStat
, st
);
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");
528 static struct timespec
stat_mtimespec(const struct stat
*st
);
532 * stat <=> other_stat -> -1, 0, 1, nil
534 * Compares File::Stat objects by comparing their respective modification
537 * +nil+ is returned if +other_stat+ is not a File::Stat object
539 * f1 = File.new("f1", "w")
541 * f2 = File.new("f2", "w")
542 * f1.stat <=> f2.stat #=> -1
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);
556 if (ts1
.tv_sec
< ts2
.tv_sec
) return INT2FIX(-1);
562 #define ST2UINT(val) ((val) & ~(~1UL << (sizeof(val) * CHAR_BIT - 1)))
565 # define NUM2DEVT(v) NUM2UINT(v)
568 # define DEVT2NUM(v) UINT2NUM(v)
570 #ifndef PRI_DEVT_PREFIX
571 # define PRI_DEVT_PREFIX ""
576 * stat.dev -> integer
578 * Returns an integer representing the device on which <i>stat</i>
581 * File.stat("testfile").dev #=> 774
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
);
592 return ULL2NUM(get_stat(self
)->st_dev
);
598 * stat.dev_major -> integer
600 * Returns the major part of <code>File_Stat#dev</code> or
603 * File.stat("/dev/fd1").dev_major #=> 2
604 * File.stat("/dev/tty").dev_major #=> 5
608 rb_stat_dev_major(VALUE self
)
611 return UINT2NUM(major(get_stat(self
)->st_dev
));
619 * stat.dev_minor -> integer
621 * Returns the minor part of <code>File_Stat#dev</code> or
624 * File.stat("/dev/fd1").dev_minor #=> 1
625 * File.stat("/dev/tty").dev_minor #=> 0
629 rb_stat_dev_minor(VALUE self
)
632 return UINT2NUM(minor(get_stat(self
)->st_dev
));
640 * stat.ino -> integer
642 * Returns the inode number for <i>stat</i>.
644 * File.stat("testfile").ino #=> 1083669
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
|
657 #elif SIZEOF_STRUCT_STAT_ST_INO > SIZEOF_LONG
658 return ULL2NUM(get_stat(self
)->st_ino
);
660 return ULONG2NUM(get_stat(self
)->st_ino
);
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"
678 rb_stat_mode(VALUE self
)
680 return UINT2NUM(ST2UINT(get_stat(self
)->st_mode
));
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
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
);
711 rb_bug(":FIXME: don't know what to do");
717 * stat.uid -> integer
719 * Returns the numeric user id of the owner of <i>stat</i>.
721 * File.stat("testfile").uid #=> 501
726 rb_stat_uid(VALUE self
)
728 return UIDT2NUM(get_stat(self
)->st_uid
);
733 * stat.gid -> integer
735 * Returns the numeric group id of the owner of <i>stat</i>.
737 * File.stat("testfile").gid #=> 500
742 rb_stat_gid(VALUE self
)
744 return GIDT2NUM(get_stat(self
)->st_gid
);
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
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
);
768 return ULL2NUM(get_stat(self
)->st_rdev
);
777 * stat.rdev_major -> integer
779 * Returns the major part of <code>File_Stat#rdev</code> or
782 * File.stat("/dev/fd1").rdev_major #=> 2
783 * File.stat("/dev/tty").rdev_major #=> 5
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
));
798 * stat.rdev_minor -> integer
800 * Returns the minor part of <code>File_Stat#rdev</code> or
803 * File.stat("/dev/fd1").rdev_minor #=> 1
804 * File.stat("/dev/tty").rdev_minor #=> 0
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
));
819 * stat.size -> integer
821 * Returns the size of <i>stat</i> in bytes.
823 * File.stat("testfile").size #=> 66
827 rb_stat_size(VALUE self
)
829 return OFFT2NUM(get_stat(self
)->st_size
);
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
844 rb_stat_blksize(VALUE self
)
846 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
847 return ULONG2NUM(get_stat(self
)->st_blksize
);
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
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
);
871 return ULONG2NUM(get_stat(self
)->st_blocks
);
878 static struct timespec
879 stat_atimespec(const struct stat
*st
)
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
;
896 stat_time(const struct timespec ts
)
898 return rb_time_nano_new(ts
.tv_sec
, ts
.tv_nsec
);
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
)
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
;
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
)
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
;
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
;
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
966 # undef HAVE_STAT_BIRTHTIME
967 #endif /* defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) */
973 * Returns the last access time for this file as an object of class
976 * File.stat("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
981 rb_stat_atime(VALUE self
)
983 return stat_atime(get_stat(self
));
990 * Returns the modification time of <i>stat</i>.
992 * File.stat("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
997 rb_stat_mtime(VALUE self
)
999 return stat_mtime(get_stat(self
));
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
1010 * Note that on Windows (NTFS), returns creation time (birth time).
1012 * File.stat("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
1017 rb_stat_ctime(VALUE self
)
1019 return stat_ctime(get_stat(self
));
1022 #if defined(HAVE_STAT_BIRTHTIME)
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")
1033 * File.write("testfile", "bar")
1035 * File.chmod(0644, "testfile")
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
1046 rb_stat_birthtime(VALUE self
)
1048 return stat_birthtime(get_stat(self
));
1051 # define rb_stat_birthtime rb_f_notimplement
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>"
1070 rb_stat_inspect(VALUE self
)
1074 static const struct {
1076 VALUE (*func
)(VALUE
);
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
},
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
++) {
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
));
1122 rb_str_append(str
, rb_inspect(v
));
1125 rb_str_buf_cat2(str
, ">");
1130 typedef struct no_gvl_stat_data
{
1139 no_gvl_fstat(void *data
)
1141 no_gvl_stat_data
*arg
= data
;
1142 return (VALUE
)fstat(arg
->file
.fd
, arg
->st
);
1146 fstat_without_gvl(int fd
, struct stat
*st
)
1148 no_gvl_stat_data data
;
1153 return (int)(VALUE
)rb_thread_io_blocking_region(no_gvl_fstat
, &data
, fd
);
1157 no_gvl_stat(void * data
)
1159 no_gvl_stat_data
*arg
= data
;
1160 return (void *)(VALUE
)STAT(arg
->file
.path
, arg
->st
);
1164 stat_without_gvl(const char *path
, struct stat
*st
)
1166 no_gvl_stat_data data
;
1168 data
.file
.path
= path
;
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)
1178 # ifdef HAVE_SYSCALL_H
1179 # include <syscall.h>
1180 # elif defined HAVE_SYS_SYSCALL_H
1181 # include <sys/syscall.h>
1183 # if defined __linux__
1184 # include <linux/stat.h>
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
{
1200 } no_gvl_statx_data
;
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
);
1210 no_gvl_statx(void *data
)
1212 return (void *)io_blocking_statx(data
);
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
);
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
);
1234 rb_statx(VALUE file
, struct statx
*stx
, unsigned int mask
)
1239 tmp
= rb_check_convert_type_with_id(file
, T_FILE
, "IO", idTo_io
);
1242 GetOpenFile(tmp
, fptr
);
1243 result
= fstatx_without_gvl(fptr
->fd
, stx
, mask
);
1247 FilePathValue(file
);
1248 file
= rb_str_encode_ospath(file
);
1249 result
= statx_without_gvl(RSTRING_PTR(file
), stx
, mask
);
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. */
1262 statx_notimplement(const char *field_name
)
1264 rb_raise(rb_eNotImpError
,
1265 "%s is unimplemented on this filesystem",
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)
1289 # define statx_has_birthtime(st) 0
1290 #endif /* !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1291 defined(HAVE_STRUCT_STATX_STX_BTIME) */
1294 rb_stat(VALUE file
, struct stat
*st
)
1299 tmp
= rb_check_convert_type_with_id(file
, T_FILE
, "IO", idTo_io
);
1303 GetOpenFile(tmp
, fptr
);
1304 result
= fstat_without_gvl(fptr
->fd
, st
);
1308 FilePathValue(file
);
1309 file
= rb_str_encode_ospath(file
);
1310 result
= stat_without_gvl(RSTRING_PTR(file
), st
);
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
1327 rb_file_s_stat(VALUE klass
, VALUE fname
)
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
);
1343 * Returns status information for <em>ios</em> as an object of type
1346 * f = File.new("testfile")
1348 * "%o" % s.mode #=> "100644"
1349 * s.blksize #=> 4096
1350 * s.atime #=> Wed Apr 09 08:53:54 CDT 2003
1355 rb_io_stat(VALUE obj
)
1360 GetOpenFile(obj
, fptr
);
1361 if (fstat(fptr
->fd
, &st
) == -1) {
1362 rb_sys_fail_path(fptr
->pathv
);
1364 return rb_stat_new(&st
);
1369 no_gvl_lstat(void *ptr
)
1371 no_gvl_stat_data
*arg
= ptr
;
1372 return (void *)(VALUE
)lstat(arg
->file
.path
, arg
->st
);
1376 lstat_without_gvl(const char *path
, struct stat
*st
)
1378 no_gvl_stat_data data
;
1380 data
.file
.path
= path
;
1383 return IO_WITHOUT_GVL_INT(no_gvl_lstat
, &data
);
1385 #endif /* HAVE_LSTAT */
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
1401 rb_file_s_lstat(VALUE klass
, VALUE fname
)
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
);
1413 return rb_file_s_stat(klass
, fname
);
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
1432 rb_file_lstat(VALUE obj
)
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
);
1447 return rb_io_stat(obj
);
1452 rb_group_member(GETGROUPS_T gid
)
1454 #if defined(_WIN32) || !defined(HAVE_GETGROUPS)
1463 if (getgid() == gid
|| getegid() == gid
)
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
) {
1479 #endif /* defined(_WIN32) || !defined(HAVE_GETGROUPS) */
1483 # define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
1486 #if defined(S_IXGRP) && !defined(_WIN32) && !defined(__CYGWIN__)
1487 #define USE_GETEUID 1
1490 #ifndef HAVE_EACCESS
1492 eaccess(const char *path
, int mode
)
1500 /* no setuid nor setgid. run shortcut. */
1501 if (getuid() == euid
&& getgid() == getegid())
1502 return access(path
, mode
);
1504 if (STAT(path
, &st
) < 0)
1508 /* Root can read or write any file. */
1512 /* Root can execute any file that has any one of the execute
1514 if (st
.st_mode
& S_IXUGO
)
1520 if (st
.st_uid
== euid
) /* owner */
1522 else if (rb_group_member(st
.st_gid
))
1525 if ((int)(st
.st_mode
& mode
) == mode
) return 0;
1529 return access(path
, mode
);
1530 #endif /* USE_GETEUID */
1532 #endif /* HAVE_EACCESS */
1540 nogvl_eaccess(void *ptr
)
1542 struct access_arg
*aa
= ptr
;
1544 return (void *)(VALUE
)eaccess(aa
->path
, aa
->mode
);
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
);
1557 return IO_WITHOUT_GVL_INT(nogvl_eaccess
, &aa
);
1561 nogvl_access(void *ptr
)
1563 struct access_arg
*aa
= ptr
;
1565 return (void *)(VALUE
)access(aa
->path
, aa
->mode
);
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
);
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).
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.
1610 rb_file_directory_p(VALUE obj
, VALUE fname
)
1613 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1618 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1619 if (S_ISDIR(st
.st_mode
)) return Qtrue
;
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
1636 rb_file_pipe_p(VALUE obj
, VALUE fname
)
1640 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
1645 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1646 if (S_ISFIFO(st
.st_mode
)) return Qtrue
;
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
1665 rb_file_symlink_p(VALUE obj
, VALUE fname
)
1669 # define S_ISLNK(m) _S_ISLNK(m)
1672 # define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
1675 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
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
;
1695 * File.socket?(filepath) -> true or false
1697 * Returns +true+ if +filepath+ points to a socket, +false+ otherwise:
1700 * File.socket?(Socket.new(:INET, :STREAM)) # => true
1701 * File.socket?(File.new('t.txt')) # => false
1706 rb_file_socket_p(VALUE obj
, VALUE fname
)
1710 # define S_ISSOCK(m) _S_ISSOCK(m)
1713 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
1716 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
1725 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1726 if (S_ISSOCK(st
.st_mode
)) return Qtrue
;
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
1744 rb_file_blockdev_p(VALUE obj
, VALUE fname
)
1748 # define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
1750 # define S_ISBLK(m) (0) /* anytime false */
1757 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1758 if (S_ISBLK(st
.st_mode
)) return Qtrue
;
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
1775 rb_file_chardev_p(VALUE obj
, VALUE fname
)
1778 # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
1783 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1784 if (S_ISCHR(st
.st_mode
)) return Qtrue
;
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.
1801 rb_file_exist_p(VALUE obj
, VALUE fname
)
1805 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
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.
1821 rb_file_readable_p(VALUE obj
, VALUE fname
)
1823 return RBOOL(rb_eaccess(fname
, R_OK
) >= 0);
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.
1838 rb_file_readable_real_p(VALUE obj
, VALUE fname
)
1840 return RBOOL(rb_access(fname
, R_OK
) >= 0);
1844 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1848 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
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"
1868 rb_file_world_readable_p(VALUE obj
, VALUE fname
)
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
));
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.
1893 rb_file_writable_p(VALUE obj
, VALUE fname
)
1895 return RBOOL(rb_eaccess(fname
, W_OK
) >= 0);
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.
1910 rb_file_writable_real_p(VALUE obj
, VALUE fname
)
1912 return RBOOL(rb_access(fname
, W_OK
) >= 0);
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"
1932 rb_file_world_writable_p(VALUE obj
, VALUE fname
)
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
));
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.
1961 rb_file_executable_p(VALUE obj
, VALUE fname
)
1963 return RBOOL(rb_eaccess(fname
, X_OK
) >= 0);
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.
1982 rb_file_executable_real_p(VALUE obj
, VALUE fname
)
1984 return RBOOL(rb_access(fname
, X_OK
) >= 0);
1988 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
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.
2004 rb_file_file_p(VALUE obj
, VALUE fname
)
2008 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2009 return RBOOL(S_ISREG(st
.st_mode
));
2014 * File.zero?(file_name) -> true or false
2016 * Returns <code>true</code> if the named file exists and has
2019 * _file_name_ can be an IO object.
2023 rb_file_zero_p(VALUE obj
, VALUE fname
)
2027 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2028 return RBOOL(st
.st_size
== 0);
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
2038 * _file_name_ can be an IO object.
2042 rb_file_size_p(VALUE obj
, VALUE fname
)
2046 if (rb_stat(fname
, &st
) < 0) return Qnil
;
2047 if (st
.st_size
== 0) return Qnil
;
2048 return OFFT2NUM(st
.st_size
);
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
2059 * _file_name_ can be an IO object.
2063 rb_file_owned_p(VALUE obj
, VALUE fname
)
2067 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2068 return RBOOL(st
.st_uid
== geteuid());
2072 rb_file_rowned_p(VALUE obj
, VALUE fname
)
2076 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2077 return RBOOL(st
.st_uid
== getuid());
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.
2092 rb_file_grpowned_p(VALUE obj
, VALUE fname
)
2097 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2098 if (rb_group_member(st
.st_gid
)) return Qtrue
;
2103 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2105 check3rdbyte(VALUE fname
, int mode
)
2109 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2110 return RBOOL(st
.st_mode
& mode
);
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.
2124 rb_file_suid_p(VALUE obj
, VALUE fname
)
2127 return check3rdbyte(fname
, S_ISUID
);
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.
2143 rb_file_sgid_p(VALUE obj
, VALUE fname
)
2146 return check3rdbyte(fname
, S_ISGID
);
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.
2162 rb_file_sticky_p(VALUE obj
, VALUE fname
)
2165 return check3rdbyte(fname
, S_ISVTX
);
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.
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
2187 * p File.identical?("a", "d") #=> false
2191 rb_file_identical_p(VALUE obj
, VALUE fname1
, VALUE fname2
)
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
;
2202 extern VALUE
rb_w32_file_identical_p(VALUE
, VALUE
);
2203 return rb_w32_file_identical_p(fname1
, fname2
);
2209 * File.size(file_name) -> integer
2211 * Returns the size of <code>file_name</code>.
2213 * _file_name_ can be an IO object.
2217 rb_file_s_size(VALUE klass
, VALUE fname
)
2221 if (rb_stat(fname
, &st
) < 0) {
2223 FilePathValue(fname
);
2224 rb_syserr_fail_path(e
, fname
);
2226 return OFFT2NUM(st
.st_size
);
2230 rb_file_ftype(const struct stat
*st
)
2234 if (S_ISREG(st
->st_mode
)) {
2237 else if (S_ISDIR(st
->st_mode
)) {
2240 else if (S_ISCHR(st
->st_mode
)) {
2241 t
= "characterSpecial";
2244 else if (S_ISBLK(st
->st_mode
)) {
2249 else if (S_ISFIFO(st
->st_mode
)) {
2254 else if (S_ISLNK(st
->st_mode
)) {
2259 else if (S_ISSOCK(st
->st_mode
)) {
2267 return rb_usascii_str_new2(t
);
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"
2286 rb_file_s_ftype(VALUE klass
, VALUE fname
)
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
);
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
2312 rb_file_s_atime(VALUE klass
, VALUE fname
)
2316 if (rb_stat(fname
, &st
) < 0) {
2318 FilePathValue(fname
);
2319 rb_syserr_fail_path(e
, fname
);
2321 return stat_atime(&st
);
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
2336 rb_file_atime(VALUE obj
)
2341 GetOpenFile(obj
, fptr
);
2342 if (fstat(fptr
->fd
, &st
) == -1) {
2343 rb_sys_fail_path(fptr
->pathv
);
2345 return stat_atime(&st
);
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
2361 rb_file_s_mtime(VALUE klass
, VALUE fname
)
2365 if (rb_stat(fname
, &st
) < 0) {
2367 FilePathValue(fname
);
2368 rb_syserr_fail_path(e
, fname
);
2370 return stat_mtime(&st
);
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
2384 rb_file_mtime(VALUE obj
)
2389 GetOpenFile(obj
, fptr
);
2390 if (fstat(fptr
->fd
, &st
) == -1) {
2391 rb_sys_fail_path(fptr
->pathv
);
2393 return stat_mtime(&st
);
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
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
2413 rb_file_s_ctime(VALUE klass
, VALUE fname
)
2417 if (rb_stat(fname
, &st
) < 0) {
2419 FilePathValue(fname
);
2420 rb_syserr_fail_path(e
, fname
);
2422 return stat_ctime(&st
);
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
2439 rb_file_ctime(VALUE obj
)
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)
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.
2467 rb_file_s_birthtime(VALUE klass
, VALUE fname
)
2471 if (rb_statx(fname
, &st
, STATX_BTIME
) < 0) {
2473 FilePathValue(fname
);
2474 rb_syserr_fail_path(e
, fname
);
2476 return statx_birthtime(&st
, fname
);
2479 # define rb_file_s_birthtime rb_f_notimplement
2482 #if defined(HAVE_STAT_BIRTHTIME)
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.
2496 rb_file_birthtime(VALUE obj
)
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
);
2508 # define rb_file_birthtime rb_f_notimplement
2512 rb_file_size(VALUE file
)
2514 if (RB_TYPE_P(file
, T_FILE
)) {
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
);
2530 return NUM2OFFT(rb_funcall(file
, idSize
, 0));
2536 * file.size -> integer
2538 * Returns the size of <i>file</i> in bytes.
2540 * File.new("testfile").size #=> 66
2545 file_size(VALUE self
)
2547 return OFFT2NUM(rb_file_size(self
));
2550 struct nogvl_chmod_data
{
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
;
2564 rb_chmod(const char *path
, mode_t mode
)
2566 struct nogvl_chmod_data data
= {
2570 return IO_WITHOUT_GVL_INT(nogvl_chmod
, &data
);
2574 chmod_internal(const char *path
, void *mode
)
2576 return chmod(path
, *(mode_t
*)mode
);
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
2589 * File.chmod(0644, "testfile", "out") #=> 2
2593 rb_file_s_chmod(int argc
, VALUE
*argv
, VALUE _
)
2598 mode
= NUM2MODET(*argv
++);
2600 return apply2files(chmod_internal
, argc
, argv
, &mode
);
2604 struct nogvl_fchmod_data
{
2610 io_blocking_fchmod(void *ptr
)
2612 struct nogvl_fchmod_data
*data
= ptr
;
2613 int ret
= fchmod(data
->fd
, data
->mode
);
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
);
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
2640 rb_file_chmod(VALUE obj
, VALUE vmode
)
2644 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2648 mode
= NUM2MODET(vmode
);
2650 GetOpenFile(obj
, fptr
);
2652 if (rb_fchmod(fptr
->fd
, mode
) == -1) {
2653 if (HAVE_FCHMOD
|| errno
!= ENOSYS
)
2654 rb_sys_fail_path(fptr
->pathv
);
2657 if (!HAVE_FCHMOD
) return INT2FIX(0);
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
);
2670 #if defined(HAVE_LCHMOD)
2672 lchmod_internal(const char *path
, void *mode
)
2674 return lchmod(path
, *(mode_t
*)mode
);
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.
2688 rb_file_s_lchmod(int argc
, VALUE
*argv
, VALUE _
)
2693 mode
= NUM2MODET(*argv
++);
2695 return apply2files(lchmod_internal
, argc
, argv
, &mode
);
2698 #define rb_file_s_lchmod rb_f_notimplement
2701 static inline rb_uid_t
2705 return (rb_uid_t
)-1;
2710 static inline rb_gid_t
2714 return (rb_gid_t
)-1;
2725 chown_internal(const char *path
, void *arg
)
2727 struct chown_args
*args
= arg
;
2728 return chown(path
, args
->owner
, args
->group
);
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")
2747 rb_file_s_chown(int argc
, VALUE
*argv
, VALUE _
)
2749 struct chown_args arg
;
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
{
2763 struct chown_args
new;
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
);
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
);
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
);
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
= {
2797 .new = {.owner
= owner
, .group
= group
},
2799 return IO_WITHOUT_GVL_INT(nogvl_fchown
, &data
);
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)
2819 rb_file_chown(VALUE obj
, VALUE owner
, VALUE group
)
2830 GetOpenFile(obj
, fptr
);
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
);
2837 if (rb_fchown(fptr
->fd
, o
, g
) == -1)
2838 rb_sys_fail_path(fptr
->pathv
);
2844 #if defined(HAVE_LCHOWN)
2846 lchown_internal(const char *path
, void *arg
)
2848 struct chown_args
*args
= arg
;
2849 return lchown(path
, args
->owner
, args
->group
);
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.
2864 rb_file_s_lchown(int argc
, VALUE
*argv
, VALUE _
)
2866 struct chown_args arg
;
2869 arg
.owner
= to_uid(*argv
++);
2870 arg
.group
= to_gid(*argv
++);
2872 return apply2files(lchown_internal
, argc
, argv
, &arg
);
2875 #define rb_file_s_lchown rb_f_notimplement
2879 const struct timespec
* tsp
;
2881 int follow
; /* Whether to act on symlinks (1) or their referent (0) */
2885 NORETURN(static void utime_failed(struct apply_arg
*));
2888 utime_failed(struct apply_arg
*aa
)
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
;
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
;
2909 e
[0] = rb_str_plus(a
, rb_str_new_cstr(" or "));
2910 rb_str_append(e
[0], m
);
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
*
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 */
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;
2968 const int try_utimensat_follow
= 0;
2970 # endif /* __APPLE__ */
2973 if (v
->follow
? try_utimensat_follow
: try_utimensat
) {
2974 # ifdef AT_SYMLINK_NOFOLLOW
2976 flags
= AT_SYMLINK_NOFOLLOW
;
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 */
2990 # endif /* TRY_UTIMESAT */
2993 #endif /* defined(HAVE_UTIMENSAT) */
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);
3003 if (v
->follow
) return lutimes(path
, tvp
);
3005 return utimes(path
, tvp
);
3008 #else /* !defined(HAVE_UTIMES) */
3010 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
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
;
3024 utbuf
.actime
= tsp
[0].tv_sec
;
3025 utbuf
.modtime
= tsp
[1].tv_sec
;
3028 return utime(path
, utp
);
3030 #endif /* !defined(HAVE_UTIMES) */
3033 utime_internal_i(int argc
, VALUE
*argv
, int follow
)
3035 struct utime_args args
;
3036 struct timespec tss
[2], *tsp
= NULL
;
3039 args
.atime
= *argv
++;
3040 args
.mtime
= *argv
++;
3042 args
.follow
= follow
;
3044 if (!NIL_P(args
.atime
) || !NIL_P(args
.mtime
)) {
3046 tsp
[0] = rb_time_timespec(args
.atime
);
3047 if (args
.atime
== args
.mtime
)
3050 tsp
[1] = rb_time_timespec(args
.mtime
);
3054 return apply2files(utime_internal
, argc
, argv
, &args
);
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.
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)))
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.
3088 rb_file_s_lutime(int argc
, VALUE
*argv
, VALUE _
)
3090 return utime_internal_i(argc
, argv
, TRUE
);
3093 #define rb_file_s_lutime rb_f_notimplement
3096 #ifdef RUBY_FUNCTION_NAME_STRING
3097 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
3099 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
3101 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
3102 NORETURN(static void syserr_fail2_in(const char *,int,VALUE
,VALUE
));
3104 syserr_fail2_in(const char *func
, int e
, VALUE s1
, VALUE s2
)
3108 const int max_pathlen
= MAX_PATH
;
3110 const int max_pathlen
= MAXPATHLEN
;
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
);
3124 rb_syserr_fail_path(e
, str
);
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"
3142 rb_file_s_link(VALUE klass
, VALUE from
, VALUE to
)
3144 FilePathValue(from
);
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
);
3155 #define rb_file_s_link rb_f_notimplement
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
3172 rb_file_s_symlink(VALUE klass
, VALUE from
, VALUE to
)
3174 FilePathValue(from
);
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
);
3185 #define rb_file_s_symlink rb_f_notimplement
3188 #ifdef HAVE_READLINK
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"
3201 rb_file_s_readlink(VALUE klass
, VALUE path
)
3203 return rb_readlink(path
, rb_filesystem_encoding());
3206 struct readlink_arg
{
3213 nogvl_readlink(void *ptr
)
3215 struct readlink_arg
*ra
= ptr
;
3217 return (void *)(VALUE
)readlink(ra
->path
, ra
->buf
, ra
->size
);
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
);
3229 return (ssize_t
)IO_WITHOUT_GVL(nogvl_readlink
, &ra
);
3233 rb_readlink(VALUE path
, rb_encoding
*enc
)
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
3244 || (rv
< 0 && errno
== ERANGE
) /* quirky behavior of GPFS */
3247 rb_str_modify_expand(v
, size
);
3249 rb_str_set_len(v
, size
);
3253 rb_str_resize(v
, 0);
3254 rb_syserr_fail_path(e
, path
);
3256 rb_str_resize(v
, rv
);
3261 #define rb_file_s_readlink rb_f_notimplement
3265 unlink_internal(const char *path
, void *arg
)
3267 return unlink(path
);
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.
3287 rb_file_s_unlink(int argc
, VALUE
*argv
, VALUE klass
)
3289 return apply2files(unlink_internal
, argc
, argv
, 0);
3292 struct rename_args
{
3298 no_gvl_rename(void *ptr
)
3300 struct rename_args
*ra
= ptr
;
3302 return (void *)(VALUE
)rename(ra
->src
, ra
->dst
);
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
3316 rb_file_s_rename(VALUE klass
, VALUE from
, VALUE to
)
3318 struct rename_args ra
;
3321 FilePathValue(from
);
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__
3330 if (IO_WITHOUT_GVL_INT(no_gvl_rename
, &ra
) < 0) {
3335 if (chmod(ra
.dst
, 0666) == 0 &&
3336 unlink(ra
.dst
) == 0 &&
3337 rename(ra
.src
, ra
.dst
) == 0)
3341 syserr_fail2(e
, from
, to
);
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
3363 rb_file_s_umask(int argc
, VALUE
*argv
, VALUE _
)
3373 omask
= umask(NUM2MODET(argv
[0]));
3376 rb_error_arity(argc
, 0, 1);
3378 return MODET2NUM(omask
);
3384 #if defined __CYGWIN__ || defined DOSISH
3386 #define DOSISH_DRIVE_LETTER
3387 #define FILE_ALT_SEPARATOR '\\'
3389 #ifdef FILE_ALT_SEPARATOR
3390 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3392 static const char file_alt_separator
[] = {FILE_ALT_SEPARATOR
, '\0'};
3395 #define isdirsep(x) ((x) == '/')
3406 #ifndef USE_NTFS_ADS
3408 # define USE_NTFS_ADS 1
3410 # define USE_NTFS_ADS 0
3415 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3417 #define istrailinggarbage(x) 0
3421 # define isADS(x) ((x) == ':')
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]))
3432 #define has_unc(buf) 0
3435 #ifdef DOSISH_DRIVE_LETTER
3437 has_drive_letter(const char *buf
)
3439 if (ISALPHA(buf
[0]) && buf
[1] == ':') {
3449 getcwdofdrv(int drv
)
3452 char *drvcwd
, *oldcwd
;
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();
3469 /* perhaps the drive is not exist. we return only drive letter */
3470 drvcwd
= strdup(drive
);
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
);
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;
3496 while (path
< end
&& isdirsep(*path
)) path
++;
3497 return (char *)path
;
3500 #define nextdirsep rb_enc_path_next
3502 rb_enc_path_next(const char *s
, const char *e
, rb_encoding
*enc
)
3504 while (s
< e
&& !isdirsep(*s
)) {
3510 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3511 #define skipprefix rb_enc_path_skip_prefix
3513 #define skipprefix(path, end, enc) (path)
3516 rb_enc_path_skip_prefix(const char *path
, const char *end
, rb_encoding
*enc
)
3518 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3520 if (path
+ 2 <= end
&& isdirsep(path
[0]) && isdirsep(path
[1])) {
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
;
3528 #ifdef DOSISH_DRIVE_LETTER
3529 if (has_drive_letter(path
))
3530 return (char *)(path
+ 2);
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
++;
3544 return skiproot(path
, end
, enc
);
3548 #define strrdirsep rb_enc_path_last_separator
3550 rb_enc_path_last_separator(const char *path
, const char *end
, rb_encoding
*enc
)
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;
3561 Inc(path
, end
, enc
);
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
;
3577 Inc(path
, end
, enc
);
3580 return (char *)path
;
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
);
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
++;
3622 Inc(path
, end
, enc
);
3625 return (char *)path
;
3627 #endif /* USE_NTFS */
3629 #define BUFCHECK(cond) do {\
3632 do {buflen *= 2;} while (cond);\
3633 rb_str_resize(result, buflen);\
3634 buf = RSTRING_PTR(result);\
3636 pend = buf + buflen;\
3640 #define BUFINIT() (\
3641 p = buf = RSTRING_PTR(result),\
3642 buflen = RSTRING_LEN(result),\
3646 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3648 # define SKIPPATHSEP(p) 1
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); \
3656 memcpy(p, (srcptr), (srclen)); \
3660 #define WITH_ROOTDIFF(stmt) do { \
3661 long rootdiff = root - buf; \
3663 root = buf + rootdiff; \
3667 copy_home_path(VALUE result
, const char *dir
)
3670 #if defined DOSISH || defined __CYGWIN__
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
)) {
3694 rb_home_dir_of(VALUE user
, VALUE result
)
3697 struct passwd
*pwPtr
;
3699 extern char *getlogin(void);
3700 const char *pwPtr
= 0;
3701 # define endpwent() ((void)0)
3703 const char *dir
, *username
= RSTRING_PTR(user
);
3704 rb_encoding
*enc
= rb_enc_get(user
);
3706 rb_encoding
*fsenc
= rb_utf8_encoding();
3708 rb_encoding
*fsenc
= rb_filesystem_encoding();
3711 dir
= username
= RSTRING_PTR(rb_str_conv_enc(user
, enc
, fsenc
));
3715 pwPtr
= getpwnam(username
);
3717 if (strcasecmp(username
, getlogin()) == 0)
3718 dir
= pwPtr
= getenv("HOME");
3722 rb_raise(rb_eArgError
, "user %"PRIsVALUE
" doesn't exist", user
);
3725 dir
= pwPtr
->pw_dir
;
3727 copy_home_path(result
, dir
);
3732 #ifndef _WIN32 /* this encompasses rb_file_expand_path_internal */
3734 rb_default_home_dir(VALUE result
)
3736 const char *dir
= getenv("HOME");
3738 #if defined HAVE_PWD_H
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());
3773 copy_home_path(result
, RSTRING_PTR(pw_dir
));
3774 rb_str_resize(pw_dir
, 0);
3777 #endif /* defined HAVE_PWD_H */
3779 rb_raise(rb_eArgError
, "couldn't find HOME environment -- expanding '~'");
3781 return copy_home_path(result
, dir
);
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
);
3792 return rb_enc_str_new(ptr
, len
, fsenc
);
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
)) {
3807 /* rb_enc_check must raise because the two encodings are not
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
);
3822 do {buflen
*= 2;} while (dirlen
> buflen
);
3823 rb_str_resize(result
, buflen
);
3824 buf
= RSTRING_PTR(result
);
3825 memcpy(buf
, cwdp
, dirlen
);
3827 if (!NIL_P(dirname
)) rb_str_resize(dirname
, 0);
3828 rb_enc_associate(result
, *enc
);
3829 return buf
+ dirlen
;
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
);
3845 if (s
[0] == '~' && abs_mode
== 0) { /* execute only if NOT absolute_path() */
3847 if (isdirsep(s
[1]) || s
[1] == '\0') {
3850 rb_str_set_len(result
, 0);
3852 rb_default_home_dir(result
);
3855 s
= nextdirsep(b
= s
, fend
, enc
);
3856 b
++; /* b[0] is '~' */
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
);
3867 if (!rb_is_absolute_path(RSTRING_PTR(result
))) {
3869 rb_enc_raise(enc
, rb_eArgError
, "non-absolute home of %.*s%.0"PRIsVALUE
,
3870 (int)userlen
, b
, fname
);
3873 rb_raise(rb_eArgError
, "non-absolute home");
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
);
3889 rb_enc_copy(result
, fname
);
3892 /* specified drive, but not full path */
3894 if (!NIL_P(dname
) && !not_same_drive(dname
, s
[0])) {
3895 rb_file_expand_path_internal(dname
, Qnil
, abs_mode
, long_name
, result
);
3897 if (has_drive_letter(p
) && TOLOWER(p
[0]) == TOLOWER(s
[0])) {
3898 /* ok, same drive */
3903 char *e
= append_fspath(result
, fname
, getcwdofdrv(*s
), &enc
, fsenc
);
3908 rb_enc_associate(result
, enc
= fs_enc_check(result
, fname
));
3911 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
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
));
3924 char *e
= append_fspath(result
, fname
, ruby_getcwd(), &enc
, fsenc
);
3928 #if defined DOSISH || defined __CYGWIN__
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
);
3935 #endif /* defined DOSISH || defined __CYGWIN__ */
3936 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
3941 do s
++; while (isdirsep(*s
));
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] == '/')
3952 rb_str_set_len(result
, p
-buf
);
3953 BUFCHECK(bdiff
+ 1 >= buflen
);
3957 rb_str_set_len(result
, p
-buf
+1);
3958 BUFCHECK(bdiff
+ 1 >= buflen
);
3960 root
= skipprefix(buf
, p
+1, enc
);
3966 if (b
== s
++) { /* beginning of path element */
3972 if (*(s
+1) == '\0' || isdirsep(*(s
+1))) {
3973 /* We must go back to the parent */
3976 if (!(n
= strrdirsep(root
, p
, enc
))) {
3986 do ++s
; while (istrailinggarbage(*s
));
3988 #endif /* USE_NTFS */
3991 #if defined DOSISH || defined __CYGWIN__
3997 /* ordinary path element, beginning don't move */
4006 while (s
< fend
&& istrailinggarbage(*s
)) s
++;
4013 #endif /* USE_NTFS */
4016 #if defined DOSISH || defined __CYGWIN__
4020 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
4028 int n
= ignored_char_p(s
, fend
, enc
);
4031 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
4038 #endif /* __APPLE__ */
4047 static const char prime
[] = ":$DATA";
4048 enum {prime_len
= sizeof(prime
) -1};
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 */
4065 rb_str_set_len(result
, p
-buf
);
4067 if (p
== skiproot(buf
, p
+ !!*p
, enc
) - 1) p
++;
4071 if ((s
= strrdirsep(b
= buf
, p
, enc
)) != 0 && !strpbrk(s
, "*?")) {
4076 WIN32_FIND_DATAW wfd
;
4079 #ifdef HAVE_CYGWIN_CONV_PATH
4080 char *w32buf
= NULL
;
4081 const int flags
= CCP_POSIX_TO_WIN_A
| CCP_RELATIVE
;
4083 char w32buf
[MAXPATHLEN
];
4084 #endif /* HAVE_CYGWIN_CONV_PATH */
4087 int lnk_added
= 0, is_symlink
= 0;
4091 if (lstat_without_gvl(buf
, &st
) == 0 && S_ISLNK(st
.st_mode
)) {
4093 if (len
> 4 && STRCASECMP(p
+ len
- 4, ".lnk") != 0) {
4097 path
= *buf
? buf
: "/";
4098 #ifdef HAVE_CYGWIN_CONV_PATH
4099 bufsize
= cygwin_conv_path(flags
, path
, NULL
, 0);
4102 if (lnk_added
) bufsize
+= 4;
4103 w32buf
= ALLOCA_N(char, bufsize
);
4104 if (cygwin_conv_path(flags
, path
, w32buf
, bufsize
) == 0) {
4108 #else /* !HAVE_CYGWIN_CONV_PATH */
4109 bufsize
= MAXPATHLEN
;
4110 if (cygwin_conv_to_win32_path(path
, w32buf
) == 0) {
4113 #endif /* !HAVE_CYGWIN_CONV_PATH */
4114 if (is_symlink
&& b
== w32buf
) {
4116 strlcat(w32buf
, p
, bufsize
);
4118 strlcat(w32buf
, ".lnk", bufsize
);
4125 #endif /* __CYGWIN__ */
4126 rb_str_set_len(result
, p
- buf
+ strlen(p
));
4127 encidx
= ENCODING_GET(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
);
4138 if (h
!= INVALID_HANDLE_VALUE
) {
4141 len
= lstrlenW(wfd
.cFileName
);
4143 if (lnk_added
&& len
> 4 &&
4144 wcscasecmp(wfd
.cFileName
+ len
- 4, L
".lnk") == 0) {
4145 wfd
.cFileName
[len
-= 4] = L
'\0';
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
);
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
);
4163 rb_str_resize(tmp
, 0);
4173 #endif /* USE_NTFS */
4175 rb_str_set_len(result
, p
- buf
);
4176 rb_enc_check(fname
, result
);
4177 ENC_CODERANGE_CLEAR(result
);
4180 #endif /* !_WIN32 (this ifdef started above rb_default_home_dir) */
4182 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, 1)
4185 str_shrink(VALUE str
)
4187 rb_str_resize(str
, RSTRING_LEN(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))))
4199 file_expand_path_1(VALUE fname
)
4201 return rb_file_expand_path_internal(fname
, Qnil
, 0, 0, EXPAND_PATH_BUFFER());
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());
4212 rb_file_expand_path_fast(VALUE fname
, VALUE dname
)
4214 return expand_path(fname
, dname
, 0, 0, EXPAND_PATH_BUFFER());
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
);
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+.
4253 s_expand_path(int c
, const VALUE
* v
, VALUE _
)
4255 return rb_file_s_expand_path(c
, v
);
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());
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
);
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"
4286 s_absolute_path(int c
, const VALUE
* v
, VALUE _
)
4288 return rb_file_s_absolute_path(c
, v
);
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)
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
;
4310 enum rb_realpath_mode
{
4314 RB_REALPATH_MODE_MAX
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
);
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
);
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
, "/");
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
) {
4364 rb_syserr_fail_path(ELOOP
, testpath
);
4367 *resolvedp
= rb_str_dup(checkval
);
4373 ret
= lstat_without_gvl(RSTRING_PTR(testpath
), &sbuf
);
4376 if (e
== ENOENT
&& !NIL_P(fallback
)) {
4377 if (stat_without_gvl(RSTRING_PTR(fallback
), &sbuf
) == 0) {
4378 rb_str_replace(*resolvedp
, fallback
);
4382 if (mode
== RB_REALPATH_CHECK
) return -1;
4384 if (mode
== RB_REALPATH_STRICT
|| !last
|| *unresolved_firstsep
)
4385 rb_syserr_fail_path(e
, testpath
);
4386 *resolvedp
= testpath
;
4390 rb_syserr_fail_path(e
, testpath
);
4393 #ifdef HAVE_READLINK
4394 if (S_ISLNK(sbuf
.st_mode
)) {
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
);
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
);
4411 *prefixlenp
= link_prefixlen
;
4413 if (realpath_rec(prefixlenp
, resolvedp
, link_names
, testpath
,
4414 loopcheck
, mode
, !*unresolved_firstsep
))
4416 RB_GC_GUARD(link_orig
);
4417 rb_hash_aset(loopcheck
, testpath
, rb_str_dup_frozen(*resolvedp
));
4420 #endif /* HAVE_READLINK */
4422 VALUE s
= rb_str_dup_frozen(testpath
);
4423 rb_hash_aset(loopcheck
, s
, s
);
4424 *resolvedp
= testpath
;
4433 rb_check_realpath_emulate(VALUE basedir
, VALUE path
, rb_encoding
*origenc
, enum rb_realpath_mode mode
)
4437 VALUE unresolved_path
;
4439 VALUE curdir
= Qnil
;
4442 char *path_names
= NULL
, *basedir_names
= NULL
, *curdir_names
= NULL
;
4443 char *ptr
, *prefixptr
= NULL
, *pend
;
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
);
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
);
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
);
4477 RSTRING_GETMEM(resolved
, prefixptr
, prefixlen
);
4478 pend
= prefixptr
+ prefixlen
;
4479 ptr
= chompdirsep(prefixptr
, pend
, enc
);
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
) {
4489 Inc(prefixptr
, pend
, enc
);
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();
4501 if (realpath_rec(&prefixlen
, &resolved
, curdir_names
, Qnil
, loopcheck
, mode
, 0))
4504 if (basedir_names
) {
4505 if (realpath_rec(&prefixlen
, &resolved
, basedir_names
, Qnil
, loopcheck
, mode
, 0))
4508 if (realpath_rec(&prefixlen
, &resolved
, path_names
, Qnil
, loopcheck
, mode
, 1))
4511 if (origenc
&& origenc
!= rb_enc_get(resolved
)) {
4512 if (rb_enc_str_asciionly_p(resolved
)) {
4513 rb_enc_associate(resolved
, origenc
);
4516 resolved
= rb_str_conv_enc(resolved
, NULL
, origenc
);
4520 RB_GC_GUARD(unresolved_path
);
4521 RB_GC_GUARD(curdir
);
4525 static VALUE
rb_file_join(VALUE ary
);
4527 #ifndef HAVE_REALPATH
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
);
4536 rb_check_realpath_emulate_rescue(VALUE arg
, VALUE exc
)
4540 #endif /* HAVE_REALPATH */
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
;
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,
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
) {
4574 rb_sys_fail_path(unresolved_path
);
4576 resolved
= ospath_new(resolved_ptr
, strlen(resolved_ptr
), rb_filesystem_encoding());
4579 # if !defined(__LINUX__) && !defined(__APPLE__)
4580 /* As `resolved` is a String in the filesystem encoding, no
4581 * conversion is needed */
4583 if (stat_without_gvl(RSTRING_PTR(resolved
), &st
) < 0) {
4584 if (mode
== RB_REALPATH_CHECK
) {
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
);
4607 #else /* !HAVE_REALPATH */
4608 if (mode
== RB_REALPATH_CHECK
) {
4612 arg
[2] = (VALUE
)origenc
;
4614 return rb_rescue(rb_check_realpath_emulate_try
, (VALUE
)arg
,
4615 rb_check_realpath_emulate_rescue
, Qnil
);
4618 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4620 #endif /* HAVE_REALPATH */
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
);
4632 rb_check_realpath(VALUE basedir
, VALUE path
, rb_encoding
*enc
)
4634 return rb_check_realpath_internal(basedir
, path
, enc
, RB_REALPATH_CHECK
);
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
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);
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.
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);
4681 rmext(const char *p
, long l0
, long l1
, const char *e
, long l2
, rb_encoding
*enc
)
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
;
4696 if (rb_enc_codepoint_len(s
, e
, &len1
, enc
) == c
) last
= s
;
4701 if (l1
< l2
) return l1
;
4704 if (!at_char_boundary(p
, s
, p
+l1
, enc
)) return 0;
4705 #if CASEFOLD_FILESYSTEM
4706 #define fncomp strncasecmp
4708 #define fncomp strncmp
4710 if (fncomp(s
, e
, l2
) == 0) {
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
4725 end
= name
+ (alllen
? (size_t)*alllen
: strlen(name
));
4726 name
= skipprefix(name
, end
, enc
);
4727 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4730 while (isdirsep(*name
))
4735 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4739 #ifdef DOSISH_DRIVE_LETTER
4740 else if (*p
== ':') {
4744 #endif /* DOSISH_DRIVE_LETTER */
4749 #endif /* DOSISH_UNC */
4750 #endif /* defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC */
4753 if (!(p
= strrdirsep(name
, end
, enc
))) {
4757 while (isdirsep(*p
)) p
++; /* skip last / */
4760 n
= ntfs_tail(p
, end
, enc
) - p
;
4762 n
= chompdirsep(p
, end
, enc
) - p
;
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
;
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"
4797 rb_file_s_basename(int argc
, VALUE
*argv
, VALUE _
)
4799 VALUE fname
, fext
, basename
;
4800 const char *name
, *p
;
4805 if (rb_check_arity(argc
, 1, 2) == 2) {
4808 enc
= check_path_encoding(fext
);
4811 FilePathStringValue(fname
);
4812 if (NIL_P(fext
) || !(enc
= rb_enc_compatible(fname
, fext
))) {
4813 enc
= rb_enc_get(fname
);
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
);
4826 fp
= StringValueCStr(fext
);
4827 if (!(f
= rmext(p
, f
, n
, fp
, RSTRING_LEN(fext
), enc
))) {
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
);
4840 static VALUE
rb_file_dirname_n(VALUE fname
, int n
);
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
4857 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4858 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4862 rb_file_s_dirname(int argc
, VALUE
*argv
, VALUE klass
)
4865 if ((argc
= rb_check_arity(argc
, 1, 2)) > 1) {
4866 n
= NUM2INT(argv
[1]);
4868 return rb_file_dirname_n(argv
[0], n
);
4872 rb_file_dirname(VALUE fname
)
4874 return rb_file_dirname_n(fname
, 1);
4878 rb_file_dirname_n(VALUE fname
, int n
)
4880 const char *name
, *root
, *p
, *end
;
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
);
4893 if (root
> name
+ 1 && isdirsep(*name
))
4894 root
= skipprefix(name
= root
- 2, end
, enc
);
4896 if (root
> name
+ 1)
4899 if (n
> (end
- root
+ 1) / 2) {
4909 if (!(p
= strrdirsep(root
, end
, enc
))) p
= root
;
4912 seps
= ALLOCV_N(const char *, sepsv
, n
);
4913 for (i
= 0; i
< n
; ++i
) seps
[i
] = root
;
4915 for (p
= root
; p
< end
; ) {
4917 const char *tmp
= p
++;
4918 while (p
< end
&& isdirsep(*p
)) p
++;
4919 if (p
>= end
) break;
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
);
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);
4947 rb_enc_copy(dirname
, fname
);
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.
4958 * end with dot dot 1
4959 * .ext dot len of .ext
4960 * .ext:stream dot len of .ext without :stream (NTFS only)
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 */
4972 do name
= ++p
; while (isdirsep(*p
));
4975 while (*p
&& *p
== '.') p
++;
4977 if (*p
== '.' || istrailinggarbage(*p
)) {
4979 const char *last
= p
++, *dot
= last
;
4980 while (istrailinggarbage(*p
)) {
4981 if (*p
== '.') dot
= p
;
4984 if (!*p
|| isADS(*p
)) {
4988 if (*last
== '.' || dot
> last
) e
= dot
;
4991 e
= p
; /* get the last dot of the last component */
4992 #endif /* USE_NTFS */
4995 else if (isADS(*p
)) {
4999 else if (isdirsep(*p
))
5005 /* no dot, or the only dot is first or end? */
5006 if (!e
|| e
== name
)
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
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"
5043 rb_file_s_extname(VALUE klass
, VALUE fname
)
5045 const char *name
, *e
;
5049 FilePathStringValue(fname
);
5050 name
= StringValueCStr(fname
);
5051 len
= RSTRING_LEN(fname
);
5052 e
= ruby_enc_find_extname(name
, &len
, rb_enc_get(fname
));
5054 return rb_str_new(0, 0);
5055 extname
= rb_str_subseq(fname
, e
- name
, len
); /* keep the dot, too! */
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"
5071 rb_file_s_path(VALUE klass
, VALUE fname
)
5073 return rb_get_path(fname
);
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
5084 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
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
));
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
);
5102 rb_file_join(VALUE ary
)
5106 const char *name
, *tail
;
5110 if (RARRAY_LEN(ary
) == 0) return rb_str_new(0, 0);
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
);
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
)) {
5130 if (!checked
) check_path_encoding(tmp
);
5131 StringValueCStr(tmp
);
5135 rb_raise(rb_eArgError
, "recursive array");
5138 tmp
= rb_exec_recursive(file_inspect_join
, ary
, tmp
);
5142 FilePathStringValue(tmp
);
5145 RSTRING_GETMEM(result
, name
, len
);
5147 rb_enc_copy(result
, tmp
);
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
);
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
);
5169 * File.join(string, ...) -> string
5171 * Returns a new string formed by joining the strings using
5174 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5179 rb_file_s_join(VALUE klass
, VALUE args
)
5181 return rb_file_join(args
);
5184 #if defined(HAVE_TRUNCATE)
5185 struct truncate_arg
{
5191 nogvl_truncate(void *ptr
)
5193 struct truncate_arg
*ta
= ptr
;
5194 return (void *)(VALUE
)truncate(ta
->path
, ta
->pos
);
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
5207 * File.truncate("out", 5) #=> 0
5208 * File.size("out") #=> 5
5213 rb_file_s_truncate(VALUE klass
, VALUE path
, VALUE len
)
5215 struct truncate_arg ta
;
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
);
5225 rb_sys_fail_path(path
);
5229 #define rb_file_s_truncate rb_f_notimplement
5232 #if defined(HAVE_FTRUNCATE)
5233 struct ftruncate_arg
{
5239 nogvl_ftruncate(void *ptr
)
5241 struct ftruncate_arg
*fa
= ptr
;
5243 return (VALUE
)ftruncate(fa
->fd
, fa
->pos
);
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
5257 * File.size("out") #=> 5
5261 rb_file_truncate(VALUE obj
, VALUE len
)
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);
5273 if ((int)rb_thread_io_blocking_region(nogvl_ftruncate
, &fa
, fa
.fd
) < 0) {
5274 rb_sys_fail_path(fptr
->pathv
);
5279 #define rb_file_truncate rb_f_notimplement
5296 #include <winerror.h>
5300 rb_thread_flock(void *data
)
5303 int old_errno
= errno
;
5305 int *op
= data
, ret
= flock(op
[0], op
[1]);
5308 if (GetLastError() == ERROR_NOT_LOCKED
) {
5316 /* :markup: markdown
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`.
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.
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
5349 * f.write("#{value}\n")
5354 * # Read the counter using a shared lock.
5355 * File.open('counter', 'r') do |f|
5356 * f.flock(File::LOCK_SH)
5364 rb_file_flock(VALUE obj
, VALUE operation
)
5368 struct timeval time
;
5370 op
[1] = op1
= NUM2INT(operation
);
5371 GetOpenFile(obj
, fptr
);
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) {
5382 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5385 if (op1
& LOCK_NB
) return Qfalse
;
5388 time
.tv_usec
= 100 * 1000; /* 0.1 sec */
5389 rb_thread_wait_for(time
);
5390 rb_io_check_closed(fptr
);
5394 #if defined(ERESTART)
5400 rb_syserr_fail_path(e
, fptr
->pathv
);
5407 test_check(int n
, int argc
, VALUE
*argv
)
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)
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.
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. |
5503 rb_f_test(int argc
, VALUE
*argv
, VALUE _
)
5507 if (argc
== 0) rb_check_arity(argc
, 2, 3);
5508 cmd
= NUM2CHR(argv
[0]);
5512 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd
)) {
5516 return rb_file_blockdev_p(0, argv
[1]);
5519 return rb_file_chardev_p(0, argv
[1]);
5522 return rb_file_directory_p(0, argv
[1]);
5525 return rb_file_exist_p(0, argv
[1]);
5528 return rb_file_file_p(0, argv
[1]);
5531 return rb_file_sgid_p(0, argv
[1]);
5534 return rb_file_grpowned_p(0, argv
[1]);
5537 return rb_file_sticky_p(0, argv
[1]);
5540 return rb_file_symlink_p(0, argv
[1]);
5543 return rb_file_owned_p(0, argv
[1]);
5546 return rb_file_rowned_p(0, argv
[1]);
5549 return rb_file_pipe_p(0, argv
[1]);
5552 return rb_file_readable_p(0, argv
[1]);
5555 return rb_file_readable_real_p(0, argv
[1]);
5558 return rb_file_size_p(0, argv
[1]);
5561 return rb_file_socket_p(0, argv
[1]);
5564 return rb_file_suid_p(0, argv
[1]);
5567 return rb_file_writable_p(0, argv
[1]);
5570 return rb_file_writable_real_p(0, argv
[1]);
5573 return rb_file_executable_p(0, argv
[1]);
5576 return rb_file_executable_real_p(0, argv
[1]);
5579 return rb_file_zero_p(0, argv
[1]);
5583 if (strchr("MAC", cmd
)) {
5585 VALUE fname
= argv
[1];
5588 if (rb_stat(fname
, &st
) == -1) {
5590 FilePathValue(fname
);
5591 rb_syserr_fail_path(e
, fname
);
5596 return stat_atime(&st
);
5598 return stat_mtime(&st
);
5600 return stat_ctime(&st
);
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
;
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
);
5622 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
== t2
.tv_nsec
) return Qtrue
;
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
;
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
;
5637 /* unknown command */
5639 rb_raise(rb_eArgError
, "unknown command '%s%c'", cmd
== '\'' || cmd
== '\\' ? "\\" : "", cmd
);
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.
5661 rb_stat_s_alloc(VALUE klass
)
5663 return stat_new_0(klass
, 0);
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).
5676 rb_stat_init(VALUE obj
, VALUE fname
)
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
);
5690 rb_st
->initialized
= true;
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
;
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"
5726 rb_stat_ftype(VALUE obj
)
5728 return rb_file_ftype(get_stat(obj
));
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
5743 rb_stat_d(VALUE obj
)
5745 if (S_ISDIR(get_stat(obj
)->st_mode
)) return Qtrue
;
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.
5758 rb_stat_p(VALUE obj
)
5761 if (S_ISFIFO(get_stat(obj
)->st_mode
)) return Qtrue
;
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
5784 rb_stat_l(VALUE obj
)
5787 if (S_ISLNK(get_stat(obj
)->st_mode
)) return Qtrue
;
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
5805 rb_stat_S(VALUE obj
)
5808 if (S_ISSOCK(get_stat(obj
)->st_mode
)) return Qtrue
;
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
5828 rb_stat_b(VALUE obj
)
5831 if (S_ISBLK(get_stat(obj
)->st_mode
)) return Qtrue
;
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
5850 rb_stat_c(VALUE obj
)
5852 if (S_ISCHR(get_stat(obj
)->st_mode
)) return Qtrue
;
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
5870 rb_stat_owned(VALUE obj
)
5872 if (get_stat(obj
)->st_uid
== geteuid()) return Qtrue
;
5877 rb_stat_rowned(VALUE obj
)
5879 if (get_stat(obj
)->st_uid
== getuid()) return Qtrue
;
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
5896 rb_stat_grpowned(VALUE obj
)
5899 if (rb_group_member(get_stat(obj
)->st_gid
)) return Qtrue
;
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
5916 rb_stat_r(VALUE obj
)
5918 struct stat
*st
= get_stat(obj
);
5921 if (geteuid() == 0) return Qtrue
;
5924 if (rb_stat_owned(obj
))
5925 return RBOOL(st
->st_mode
& S_IRUSR
);
5928 if (rb_stat_grpowned(obj
))
5929 return RBOOL(st
->st_mode
& S_IRGRP
);
5932 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
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
5949 rb_stat_R(VALUE obj
)
5951 struct stat
*st
= get_stat(obj
);
5954 if (getuid() == 0) return Qtrue
;
5957 if (rb_stat_rowned(obj
))
5958 return RBOOL(st
->st_mode
& S_IRUSR
);
5961 if (rb_group_member(get_stat(obj
)->st_gid
))
5962 return RBOOL(st
->st_mode
& S_IRGRP
);
5965 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
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"
5984 rb_stat_wr(VALUE obj
)
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
));
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
6007 rb_stat_w(VALUE obj
)
6009 struct stat
*st
= get_stat(obj
);
6012 if (geteuid() == 0) return Qtrue
;
6015 if (rb_stat_owned(obj
))
6016 return RBOOL(st
->st_mode
& S_IWUSR
);
6019 if (rb_stat_grpowned(obj
))
6020 return RBOOL(st
->st_mode
& S_IWGRP
);
6023 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
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
6040 rb_stat_W(VALUE obj
)
6042 struct stat
*st
= get_stat(obj
);
6045 if (getuid() == 0) return Qtrue
;
6048 if (rb_stat_rowned(obj
))
6049 return RBOOL(st
->st_mode
& S_IWUSR
);
6052 if (rb_group_member(get_stat(obj
)->st_gid
))
6053 return RBOOL(st
->st_mode
& S_IWGRP
);
6056 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
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"
6075 rb_stat_ww(VALUE obj
)
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
));
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
6095 * File.stat("testfile").executable? #=> false
6100 rb_stat_x(VALUE obj
)
6102 struct stat
*st
= get_stat(obj
);
6105 if (geteuid() == 0) {
6106 return RBOOL(st
->st_mode
& S_IXUGO
);
6110 if (rb_stat_owned(obj
))
6111 return RBOOL(st
->st_mode
& S_IXUSR
);
6114 if (rb_stat_grpowned(obj
))
6115 return RBOOL(st
->st_mode
& S_IXGRP
);
6118 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
6125 * stat.executable_real? -> true or false
6127 * Same as <code>executable?</code>, but tests using the real owner of
6132 rb_stat_X(VALUE obj
)
6134 struct stat
*st
= get_stat(obj
);
6137 if (getuid() == 0) {
6138 return RBOOL(st
->st_mode
& S_IXUGO
);
6142 if (rb_stat_rowned(obj
))
6143 return RBOOL(st
->st_mode
& S_IXUSR
);
6146 if (rb_group_member(get_stat(obj
)->st_gid
))
6147 return RBOOL(st
->st_mode
& S_IXGRP
);
6150 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
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
6167 rb_stat_f(VALUE obj
)
6169 if (S_ISREG(get_stat(obj
)->st_mode
)) return Qtrue
;
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
6185 rb_stat_z(VALUE obj
)
6187 if (get_stat(obj
)->st_size
== 0) return Qtrue
;
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
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
);
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
6224 rb_stat_suid(VALUE obj
)
6227 if (get_stat(obj
)->st_mode
& S_ISUID
) return Qtrue
;
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
6245 rb_stat_sgid(VALUE obj
)
6248 if (get_stat(obj
)->st_mode
& S_ISGID
) return Qtrue
;
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
6266 rb_stat_sticky(VALUE obj
)
6269 if (get_stat(obj
)->st_mode
& S_ISVTX
) return Qtrue
;
6274 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6275 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6286 nogvl_mkfifo(void *ptr
)
6288 struct mkfifo_arg
*ma
= ptr
;
6290 return (void *)(VALUE
)mkfifo(ma
->path
, ma
->mode
);
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
6304 rb_file_s_mkfifo(int argc
, VALUE
*argv
, VALUE _
)
6307 struct mkfifo_arg ma
;
6310 rb_check_arity(argc
, 1, 2);
6312 ma
.mode
= NUM2MODET(argv
[1]);
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
);
6324 #define rb_file_s_mkfifo rb_f_notimplement
6327 static VALUE rb_mFConst
;
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;
6342 if (isdirsep(path
[0]) && isdirsep(path
[1])) return 1;
6345 if (path
[0] == '/') return 1;
6350 #ifndef ENABLE_PATH_CHECK
6351 # if defined DOSISH || defined __CYGWIN__
6352 # define ENABLE_PATH_CHECK 0
6354 # define ENABLE_PATH_CHECK 1
6358 #if ENABLE_PATH_CHECK
6360 path_check_0(VALUE path
)
6363 const char *p0
= StringValueCStr(path
);
6368 if (!rb_is_absolute_path(p0
)) {
6369 char *buf
= ruby_getcwd();
6372 newpath
= rb_str_new2(buf
);
6375 rb_str_cat2(newpath
, "/");
6376 rb_str_cat2(newpath
, p0
);
6378 p0
= RSTRING_PTR(path
);
6380 e0
= p0
+ RSTRING_LEN(path
);
6381 enc
= rb_enc_get(path
);
6384 # define S_IWOTH 002
6386 if (STAT(p0
, &st
) == 0 && S_ISDIR(st
.st_mode
) && (st
.st_mode
& S_IWOTH
)
6388 && !(p
&& (st
.st_mode
& S_ISVTX
))
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",
6402 s
= strrdirsep(p0
, e0
, enc
);
6404 if (!s
|| s
== p0
) return 1;
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
);
6423 p
= strchr(path
, sep
);
6427 if (!path_check_0(rb_str_new(p0
, p
- p0
))) {
6428 return 0; /* not safe */
6431 if (p0
> pend
) break;
6432 p
= strchr(p0
, sep
);
6440 ruby_is_fd_loadable(int fd
)
6447 if (fstat(fd
, &st
) < 0)
6450 if (S_ISREG(st
.st_mode
))
6453 if (S_ISFIFO(st
.st_mode
) || S_ISCHR(st
.st_mode
))
6456 if (S_ISDIR(st
.st_mode
))
6467 rb_file_load_ok(const char *path
)
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
6477 #elif defined O_NDELAY
6481 int fd
= rb_cloexec_open(path
, mode
, 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
);
6495 is_explicit_relative(const char *path
)
6497 if (*path
++ != '.') return 0;
6498 if (*path
== '.') path
++;
6499 return isdirsep(*path
);
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
);
6510 RBASIC_SET_CLASS(path
, rb_obj_class(orig
));
6516 rb_find_file_ext(VALUE
*filep
, const char *const *ext
)
6518 const char *f
= StringValueCStr(*filep
);
6519 VALUE fname
= *filep
, load_path
, tmp
;
6523 if (!ext
[0]) return 0;
6526 fname
= file_expand_path_1(fname
);
6527 f
= RSTRING_PTR(fname
);
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
);
6541 rb_str_set_len(fname
, fnlen
);
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
);
6567 rb_str_set_len(fname
, fnlen
);
6569 rb_str_resize(tmp
, 0);
6570 RB_GC_GUARD(load_path
);
6575 rb_find_file(VALUE path
)
6577 VALUE tmp
, load_path
;
6578 const char *f
= StringValueCStr(path
);
6582 tmp
= file_expand_path_1(path
);
6583 path
= copy_path_class(tmp
, path
);
6584 f
= RSTRING_PTR(path
);
6588 if (expanded
|| rb_is_absolute_path(f
) || is_explicit_relative(f
)) {
6589 if (!rb_file_load_ok(f
)) return 0;
6591 path
= copy_path_class(file_expand_path_1(path
), path
);
6595 RB_GC_GUARD(load_path
) = rb_get_expanded_load_path();
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);
6614 return 0; /* no path, no load */
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); \
6626 const char ruby_null_device
[] =
6629 #elif defined AMIGA || defined __amigaos__
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
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).
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
6721 * ===== Read/Write Modes for Existing \File
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:
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"
6740 * f.readline # => "First line\n"
6743 * f.readline # => "irst line\n"
6746 * f.readline # => "econd line\n"
6748 * - Writing is not allowed:
6750 * f.write('foo') # Raises IOError.
6754 * - \File is initially truncated:
6757 * File.write(path, text)
6758 * f = File.new(path, 'w')
6759 * f.size == 0 # => true
6761 * - File's initial write position is 0:
6765 * - \File may be written anywhere (even past end-of-file);
6766 * see IO#rewind, IO#pos=, IO#seek:
6770 * File.read(path) # => "foo"
6775 * File.read(path) # => "foobar"
6781 * File.read(path) # => "bazbar"
6787 * File.read(path) # => "bazfoo"
6793 * File.read(path) # => "bazbam"
6797 * f.write('bah') # Zero padding as needed.
6799 * File.read(path) # => "bazbam\u0000\u0000bah"
6802 * - Reading is not allowed:
6804 * f.read # Raises IOError.
6808 * - \File is not initially truncated:
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):
6819 * - \File may be written only at end-of-file;
6820 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6824 * File.read(path) # => "foobar"
6827 * File.read(path) # => "foobarbaz"
6832 * File.read(path) # => "foobarbazbat"
6834 * - Reading is not allowed:
6836 * f.read # Raises IOError.
6840 * - \File is not initially truncated:
6843 * File.write(path, text)
6844 * f = File.new(path, 'r+')
6845 * f.size == 0 # => false
6847 * - File's initial read position is 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"
6858 * f.readline # => "First line\n"
6861 * f.readline # => "irst line\n"
6864 * f.readline # => "econd line\n"
6870 * # => "WWWst line\nSecond line\nFourth line\nFifth line\n"
6876 * # => "WWWst lineXXXecond line\nFourth line\nFifth line\n"
6883 * # => #<File:t.tmp>
6885 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n"
6888 * f.write('ZZZ') # Zero padding as needed.
6891 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
6896 * - \File is not initially truncated:
6899 * File.write(path, 'foo')
6900 * f = File.new(path, 'a+')
6901 * f.size == 0 # => false
6903 * - File's initial read position is 0:
6907 * - \File may be written only at end-of-file;
6908 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6912 * File.read(path) # => "foobar"
6915 * File.read(path) # => "foobarbaz"
6920 * File.read(path) # => "foobarbazbat"
6922 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
6925 * f.read # => "foobarbazbat"
6928 * f.read # => "barbazbat"
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).
6940 * - File's initial write position is 0:
6943 * FileUtils.rm_f(path)
6944 * f = File.new(path, 'w')
6947 * - \File may be written anywhere (even past end-of-file);
6948 * see IO#rewind, IO#pos=, IO#seek:
6952 * File.read(path) # => "foo"
6957 * File.read(path) # => "foobar"
6963 * File.read(path) # => "bazbar"
6969 * File.read(path) # => "bazfoo"
6975 * File.read(path) # => "bazbam"
6979 * f.write('bah') # Zero padding as needed.
6981 * File.read(path) # => "bazbam\u0000\u0000bah"
6984 * - Reading is not allowed:
6986 * f.read # Raises IOError.
6990 * - File's initial write position is 0:
6993 * FileUtils.rm_f(path)
6994 * f = File.new(path, 'a')
6997 * - Writing occurs only at end-of-file:
7004 * File.read(path) # => "foobar"
7009 * File.read(path) # => "foobarbaz"
7011 * - Reading is not allowed:
7013 * f.read # Raises IOError.
7017 * - File's initial position is 0:
7020 * FileUtils.rm_f(path)
7021 * f = File.new(path, 'w+')
7024 * - \File may be written anywhere (even past end-of-file);
7025 * see IO#rewind, IO#pos=, IO#seek:
7029 * File.read(path) # => "foo"
7034 * File.read(path) # => "foobar"
7040 * File.read(path) # => "bazbar"
7046 * File.read(path) # => "bazfoo"
7052 * File.read(path) # => "bazbam"
7056 * f.write('bah') # Zero padding as needed.
7058 * File.read(path) # => "bazbam\u0000\u0000bah"
7061 * - \File may be read anywhere (even past end-of-file);
7062 * see IO#rewind, IO#pos=, IO#seek:
7067 * # => "bazbam\u0000\u0000bah"
7072 * # => "bam\u0000\u0000bah"
7081 * - File's initial write position is 0:
7084 * FileUtils.rm_f(path)
7085 * f = File.new(path, 'a+')
7088 * - Writing occurs only at end-of-file:
7095 * File.read(path) # => "foobar"
7100 * File.read(path) # => "foobarbaz"
7102 * - \File may be read anywhere (even past end-of-file);
7103 * see IO#rewind, IO#pos=, IO#seek:
7106 * f.read # => "foobarbaz"
7109 * f.read # => "barbaz"
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
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.
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.
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.
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.
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>
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
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)
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>.
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]
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.
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.
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+.
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
7391 * - ::world_writable?: Returns whether the file at the given path is writable
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+.
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+.
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+.
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.
7433 #if defined(__APPLE__) && defined(HAVE_WORKING_FORK)
7434 rb_CFString_class_initialize_before_fork();
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);
7518 /* platform specific alternative separator */
7519 rb_define_const(rb_cFile
, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator
)));
7521 rb_define_const(rb_cFile
, "ALT_SEPARATOR", Qnil
);
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]
7559 * \File-access constants may be used with optional argument +mode+ in calls
7560 * to the following methods:
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.
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).
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).
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
7608 * === \File Positioning
7612 * Flag File::APPEND specifies that the stream should be opened
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.
7621 * Flag File::TRUNC specifies that the stream should be truncated
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
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.
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
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;
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.
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.
7721 * Flag File::DIRECT requests that cache effects of the I/O to and from the stream
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.
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.
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.
7772 * Four file constants relate to stream locking;
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:
7801 * - Pathname#fnmatch.
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_';
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.
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
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)
7878 # define O_NONBLOCK O_NDELAY
7880 /* {File::NONBLOCK}[rdoc-ref:File::Constants@File-3A-3ANONBLOCK] */
7881 rb_define_const(rb_mFConst
, "NONBLOCK", INT2FIX(O_NONBLOCK
));
7883 /* {File::TRUNC}[rdoc-ref:File::Constants@File-3A-3ATRUNC] */
7884 rb_define_const(rb_mFConst
, "TRUNC", INT2FIX(O_TRUNC
));
7886 /* {File::NOCTTY}[rdoc-ref:File::Constants@File-3A-3ANOCTTY] */
7887 rb_define_const(rb_mFConst
, "NOCTTY", INT2FIX(O_NOCTTY
));
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
7897 /* {File::SHARE_DELETE}[rdoc-ref:File::Constants@File-3A-3ASHARE_DELETE] */
7898 rb_define_const(rb_mFConst
, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE
));
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
));
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
));
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
));
7912 /* {File::NOFOLLOW}[rdoc-ref:File::Constants@File-3A-3ANOFOLLOW] */
7913 rb_define_const(rb_mFConst
, "NOFOLLOW", INT2FIX(O_NOFOLLOW
)); /* FreeBSD, Linux */
7916 /* {File::NOATIME}[rdoc-ref:File::Constants@File-3A-3ANOATIME] */
7917 rb_define_const(rb_mFConst
, "NOATIME", INT2FIX(O_NOATIME
)); /* Linux */
7920 /* {File::DIRECT}[rdoc-ref:File::Constants@File-3A-3ADIRECT] */
7921 rb_define_const(rb_mFConst
, "DIRECT", INT2FIX(O_DIRECT
));
7924 /* {File::TMPFILE}[rdoc-ref:File::Constants@File-3A-3ATMPFILE] */
7925 rb_define_const(rb_mFConst
, "TMPFILE", INT2FIX(O_TMPFILE
));
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);