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 rename(f, t) rb_w32_urename((f), (t))
121 # define symlink(s, l) rb_w32_usymlink((s), (l))
123 # ifdef HAVE_REALPATH
124 /* Don't use native realpath(3) on Windows, as the check for
125 absolute paths does not work for drive letters. */
126 # undef HAVE_REALPATH
129 # define STAT(p, s) stat((p), (s))
132 #if defined _WIN32 || defined __APPLE__
133 # define USE_OSPATH 1
134 # define TO_OSPATH(str) rb_str_encode_ospath(str)
136 # define USE_OSPATH 0
137 # define TO_OSPATH(str) (str)
140 /* utime may fail if time is out-of-range for the FS [ruby-dev:38277] */
141 #if defined DOSISH || defined __CYGWIN__
142 # define UTIME_EINVAL
145 /* Solaris 10 realpath(3) doesn't support File.realpath */
146 #if defined HAVE_REALPATH && defined __sun && defined __SVR4
156 #include "encindex.h"
158 #include "internal.h"
159 #include "internal/compilers.h"
160 #include "internal/dir.h"
161 #include "internal/error.h"
162 #include "internal/file.h"
163 #include "internal/io.h"
164 #include "internal/load.h"
165 #include "internal/object.h"
166 #include "internal/process.h"
167 #include "internal/thread.h"
168 #include "internal/vm.h"
169 #include "ruby/encoding.h"
171 #include "ruby/thread.h"
172 #include "ruby/util.h"
179 file_path_convert(VALUE name
)
181 #ifndef _WIN32 /* non Windows == Unix */
182 int fname_encidx
= ENCODING_GET(name
);
184 if (ENCINDEX_US_ASCII
!= fname_encidx
&&
185 ENCINDEX_ASCII
!= fname_encidx
&&
186 (fs_encidx
= rb_filesystem_encindex()) != fname_encidx
&&
187 rb_default_internal_encoding() &&
188 !rb_enc_str_asciionly_p(name
)) {
189 /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */
190 /* fs_encoding should be ascii compatible */
191 rb_encoding
*fname_encoding
= rb_enc_from_index(fname_encidx
);
192 rb_encoding
*fs_encoding
= rb_enc_from_index(fs_encidx
);
193 name
= rb_str_conv_enc(name
, fname_encoding
, fs_encoding
);
200 check_path_encoding(VALUE str
)
202 rb_encoding
*enc
= rb_enc_get(str
);
203 if (!rb_enc_asciicompat(enc
)) {
204 rb_raise(rb_eEncCompatError
, "path name must be ASCII-compatible (%s): %"PRIsVALUE
,
205 rb_enc_name(enc
), rb_str_inspect(str
));
211 rb_get_path_check_to_string(VALUE obj
)
216 if (RB_TYPE_P(obj
, T_STRING
)) {
219 CONST_ID(to_path
, "to_path");
220 tmp
= rb_check_funcall_default(obj
, to_path
, 0, 0, obj
);
226 rb_get_path_check_convert(VALUE obj
)
228 obj
= file_path_convert(obj
);
230 check_path_encoding(obj
);
231 if (!rb_str_to_cstr(obj
)) {
232 rb_raise(rb_eArgError
, "path name contains null byte");
235 return rb_str_new4(obj
);
239 rb_get_path_no_checksafe(VALUE obj
)
241 return rb_get_path(obj
);
245 rb_get_path(VALUE obj
)
247 return rb_get_path_check_convert(rb_get_path_check_to_string(obj
));
251 rb_str_encode_ospath(VALUE path
)
254 int encidx
= ENCODING_GET(path
);
255 #if 0 && defined _WIN32
256 if (encidx
== ENCINDEX_ASCII
) {
257 encidx
= rb_filesystem_encindex();
260 if (encidx
!= ENCINDEX_ASCII
&& encidx
!= ENCINDEX_UTF_8
) {
261 rb_encoding
*enc
= rb_enc_from_index(encidx
);
262 rb_encoding
*utf8
= rb_utf8_encoding();
263 path
= rb_str_conv_enc(path
, enc
, utf8
);
270 # define NORMALIZE_UTF8PATH 1
272 rb_str_append_normalized_ospath(VALUE str
, const char *ptr
, long len
)
276 CFStringRef s
= CFStringCreateWithBytesNoCopy(kCFAllocatorDefault
,
277 (const UInt8
*)ptr
, len
,
278 kCFStringEncodingUTF8
, FALSE
,
280 CFMutableStringRef m
= CFStringCreateMutableCopy(kCFAllocatorDefault
, len
, s
);
281 long oldlen
= RSTRING_LEN(str
);
283 CFStringNormalize(m
, kCFStringNormalizationFormC
);
284 all
= CFRangeMake(0, CFStringGetLength(m
));
285 CFStringGetBytes(m
, all
, kCFStringEncodingUTF8
, '?', FALSE
, NULL
, 0, &buflen
);
286 rb_str_modify_expand(str
, buflen
);
287 CFStringGetBytes(m
, all
, kCFStringEncodingUTF8
, '?', FALSE
,
288 (UInt8
*)(RSTRING_PTR(str
) + oldlen
), buflen
, &buflen
);
289 rb_str_set_len(str
, oldlen
+ buflen
);
296 rb_str_normalize_ospath(const char *ptr
, long len
)
299 const char *e
= ptr
+ len
;
301 VALUE str
= rb_str_buf_new(len
);
302 rb_encoding
*enc
= rb_utf8_encoding();
303 rb_enc_associate(str
, enc
);
307 int r
= rb_enc_precise_mbclen(p
, e
, enc
);
308 if (!MBCLEN_CHARFOUND_P(r
)) {
309 /* invalid byte shall not happen but */
310 static const char invalid
[3] = "\xEF\xBF\xBD";
311 rb_str_append_normalized_ospath(str
, p1
, p
-p1
);
312 rb_str_cat(str
, invalid
, sizeof(invalid
));
317 l
= MBCLEN_CHARFOUND_LEN(r
);
318 c
= rb_enc_mbc_to_codepoint(p
, e
, enc
);
319 if ((0x2000 <= c
&& c
<= 0x2FFF) || (0xF900 <= c
&& c
<= 0xFAFF) ||
320 (0x2F800 <= c
&& c
<= 0x2FAFF)) {
322 rb_str_append_normalized_ospath(str
, p1
, p
-p1
);
324 rb_str_cat(str
, p
, l
);
333 rb_str_append_normalized_ospath(str
, p1
, p
-p1
);
340 ignored_char_p(const char *p
, const char *e
, rb_encoding
*enc
)
343 if (p
+3 > e
) return 0;
344 switch ((unsigned char)*p
) {
346 switch ((unsigned char)p
[1]) {
348 c
= (unsigned char)p
[2];
349 /* c >= 0x200c && c <= 0x200f */
350 if (c
>= 0x8c && c
<= 0x8f) return 3;
351 /* c >= 0x202a && c <= 0x202e */
352 if (c
>= 0xaa && c
<= 0xae) return 3;
355 c
= (unsigned char)p
[2];
356 /* c >= 0x206a && c <= 0x206f */
357 if (c
>= 0xaa && c
<= 0xaf) return 3;
363 if ((unsigned char)p
[1] == 0xbb &&
364 (unsigned char)p
[2] == 0xbf)
371 # define NORMALIZE_UTF8PATH 0
374 #define apply2args(n) (rb_check_arity(argc, n, UNLIMITED_ARGUMENTS), argc-=n)
376 struct apply_filename
{
385 int (*func
)(const char *, void *);
387 struct apply_filename fn
[FLEX_ARY_LEN
];
391 no_gvl_apply2files(void *ptr
)
393 struct apply_arg
*aa
= ptr
;
395 for (aa
->i
= 0; aa
->i
< aa
->argc
; aa
->i
++) {
396 if (aa
->func(aa
->fn
[aa
->i
].ptr
, aa
->arg
) < 0) {
405 NORETURN(static void utime_failed(struct apply_arg
*));
406 static int utime_internal(const char *, void *);
410 apply2files(int (*func
)(const char *, void *), int argc
, VALUE
*argv
, void *arg
)
413 const size_t size
= sizeof(struct apply_filename
);
414 const long len
= (long)(offsetof(struct apply_arg
, fn
) + (size
* argc
));
415 struct apply_arg
*aa
= ALLOCV(v
, len
);
422 for (aa
->i
= 0; aa
->i
< argc
; aa
->i
++) {
423 VALUE path
= rb_get_path(argv
[aa
->i
]);
425 path
= rb_str_encode_ospath(path
);
426 aa
->fn
[aa
->i
].ptr
= RSTRING_PTR(path
);
427 aa
->fn
[aa
->i
].path
= path
;
430 rb_thread_call_without_gvl(no_gvl_apply2files
, aa
, RUBY_UBF_IO
, 0);
433 if (func
== utime_internal
) {
437 rb_syserr_fail_path(aa
->errnum
, aa
->fn
[aa
->i
].path
);
442 return LONG2FIX(argc
);
447 * file.path -> filename
448 * file.to_path -> filename
450 * Returns the pathname used to create <i>file</i> as a string. Does
451 * not normalize the name.
453 * The pathname may not point to the file corresponding to <i>file</i>.
454 * For instance, the pathname becomes void when the file has been
457 * This method raises IOError for a <i>file</i> created using
458 * File::Constants::TMPFILE because they don't have a pathname.
460 * File.new("testfile").path #=> "testfile"
461 * File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"
466 rb_file_path(VALUE obj
)
470 fptr
= RFILE(rb_io_taint_check(obj
))->fptr
;
471 rb_io_check_initialized(fptr
);
473 if (NIL_P(fptr
->pathv
)) {
474 rb_raise(rb_eIOError
, "File is unnamed (TMPFILE?)");
477 return rb_str_dup(fptr
->pathv
);
481 stat_memsize(const void *p
)
483 return sizeof(struct stat
);
486 static const rb_data_type_t stat_data_type
= {
488 {NULL
, RUBY_TYPED_DEFAULT_FREE
, stat_memsize
,},
489 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
493 stat_new_0(VALUE klass
, const struct stat
*st
)
495 struct stat
*nst
= 0;
496 VALUE obj
= TypedData_Wrap_Struct(klass
, &stat_data_type
, 0);
499 nst
= ALLOC(struct stat
);
501 RTYPEDDATA_DATA(obj
) = nst
;
507 rb_stat_new(const struct stat
*st
)
509 return stat_new_0(rb_cStat
, st
);
516 TypedData_Get_Struct(self
, struct stat
, &stat_data_type
, st
);
517 if (!st
) rb_raise(rb_eTypeError
, "uninitialized File::Stat");
521 static struct timespec
stat_mtimespec(const struct stat
*st
);
525 * stat <=> other_stat -> -1, 0, 1, nil
527 * Compares File::Stat objects by comparing their respective modification
530 * +nil+ is returned if +other_stat+ is not a File::Stat object
532 * f1 = File.new("f1", "w")
534 * f2 = File.new("f2", "w")
535 * f1.stat <=> f2.stat #=> -1
539 rb_stat_cmp(VALUE self
, VALUE other
)
541 if (rb_obj_is_kind_of(other
, rb_obj_class(self
))) {
542 struct timespec ts1
= stat_mtimespec(get_stat(self
));
543 struct timespec ts2
= stat_mtimespec(get_stat(other
));
544 if (ts1
.tv_sec
== ts2
.tv_sec
) {
545 if (ts1
.tv_nsec
== ts2
.tv_nsec
) return INT2FIX(0);
546 if (ts1
.tv_nsec
< ts2
.tv_nsec
) return INT2FIX(-1);
549 if (ts1
.tv_sec
< ts2
.tv_sec
) return INT2FIX(-1);
555 #define ST2UINT(val) ((val) & ~(~1UL << (sizeof(val) * CHAR_BIT - 1)))
558 # define NUM2DEVT(v) NUM2UINT(v)
561 # define DEVT2NUM(v) UINT2NUM(v)
563 #ifndef PRI_DEVT_PREFIX
564 # define PRI_DEVT_PREFIX ""
569 * stat.dev -> integer
571 * Returns an integer representing the device on which <i>stat</i>
574 * File.stat("testfile").dev #=> 774
578 rb_stat_dev(VALUE self
)
580 #if SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_DEV_T
581 return DEVT2NUM(get_stat(self
)->st_dev
);
582 #elif SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_LONG
583 return ULONG2NUM(get_stat(self
)->st_dev
);
585 return ULL2NUM(get_stat(self
)->st_dev
);
591 * stat.dev_major -> integer
593 * Returns the major part of <code>File_Stat#dev</code> or
596 * File.stat("/dev/fd1").dev_major #=> 2
597 * File.stat("/dev/tty").dev_major #=> 5
601 rb_stat_dev_major(VALUE self
)
604 return UINT2NUM(major(get_stat(self
)->st_dev
));
612 * stat.dev_minor -> integer
614 * Returns the minor part of <code>File_Stat#dev</code> or
617 * File.stat("/dev/fd1").dev_minor #=> 1
618 * File.stat("/dev/tty").dev_minor #=> 0
622 rb_stat_dev_minor(VALUE self
)
625 return UINT2NUM(minor(get_stat(self
)->st_dev
));
633 * stat.ino -> integer
635 * Returns the inode number for <i>stat</i>.
637 * File.stat("testfile").ino #=> 1083669
642 rb_stat_ino(VALUE self
)
644 #ifdef HAVE_STRUCT_STAT_ST_INOHIGH
645 /* assume INTEGER_PACK_LSWORD_FIRST and st_inohigh is just next of st_ino */
646 return rb_integer_unpack(&get_stat(self
)->st_ino
, 2,
647 SIZEOF_STRUCT_STAT_ST_INO
, 0,
648 INTEGER_PACK_LSWORD_FIRST
|INTEGER_PACK_NATIVE_BYTE_ORDER
|
650 #elif SIZEOF_STRUCT_STAT_ST_INO > SIZEOF_LONG
651 return ULL2NUM(get_stat(self
)->st_ino
);
653 return ULONG2NUM(get_stat(self
)->st_ino
);
659 * stat.mode -> integer
661 * Returns an integer representing the permission bits of
662 * <i>stat</i>. The meaning of the bits is platform dependent; on
663 * Unix systems, see <code>stat(2)</code>.
665 * File.chmod(0644, "testfile") #=> 1
666 * s = File.stat("testfile")
667 * sprintf("%o", s.mode) #=> "100644"
671 rb_stat_mode(VALUE self
)
673 return UINT2NUM(ST2UINT(get_stat(self
)->st_mode
));
678 * stat.nlink -> integer
680 * Returns the number of hard links to <i>stat</i>.
682 * File.stat("testfile").nlink #=> 1
683 * File.link("testfile", "testfile.bak") #=> 0
684 * File.stat("testfile").nlink #=> 2
689 rb_stat_nlink(VALUE self
)
691 /* struct stat::st_nlink is nlink_t in POSIX. Not the case for Windows. */
692 const struct stat
*ptr
= get_stat(self
);
694 if (sizeof(ptr
->st_nlink
) <= sizeof(int)) {
695 return UINT2NUM((unsigned)ptr
->st_nlink
);
697 else if (sizeof(ptr
->st_nlink
) == sizeof(long)) {
698 return ULONG2NUM((unsigned long)ptr
->st_nlink
);
700 else if (sizeof(ptr
->st_nlink
) == sizeof(LONG_LONG
)) {
701 return ULL2NUM((unsigned LONG_LONG
)ptr
->st_nlink
);
704 rb_bug(":FIXME: don't know what to do");
710 * stat.uid -> integer
712 * Returns the numeric user id of the owner of <i>stat</i>.
714 * File.stat("testfile").uid #=> 501
719 rb_stat_uid(VALUE self
)
721 return UIDT2NUM(get_stat(self
)->st_uid
);
726 * stat.gid -> integer
728 * Returns the numeric group id of the owner of <i>stat</i>.
730 * File.stat("testfile").gid #=> 500
735 rb_stat_gid(VALUE self
)
737 return GIDT2NUM(get_stat(self
)->st_gid
);
742 * stat.rdev -> integer or nil
744 * Returns an integer representing the device type on which
745 * <i>stat</i> resides. Returns <code>nil</code> if the operating
746 * system doesn't support this feature.
748 * File.stat("/dev/fd1").rdev #=> 513
749 * File.stat("/dev/tty").rdev #=> 1280
753 rb_stat_rdev(VALUE self
)
755 #ifdef HAVE_STRUCT_STAT_ST_RDEV
756 # if SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_DEV_T
757 return DEVT2NUM(get_stat(self
)->st_rdev
);
758 # elif SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_LONG
759 return ULONG2NUM(get_stat(self
)->st_rdev
);
761 return ULL2NUM(get_stat(self
)->st_rdev
);
770 * stat.rdev_major -> integer
772 * Returns the major part of <code>File_Stat#rdev</code> or
775 * File.stat("/dev/fd1").rdev_major #=> 2
776 * File.stat("/dev/tty").rdev_major #=> 5
780 rb_stat_rdev_major(VALUE self
)
782 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(major)
783 return UINT2NUM(major(get_stat(self
)->st_rdev
));
791 * stat.rdev_minor -> integer
793 * Returns the minor part of <code>File_Stat#rdev</code> or
796 * File.stat("/dev/fd1").rdev_minor #=> 1
797 * File.stat("/dev/tty").rdev_minor #=> 0
801 rb_stat_rdev_minor(VALUE self
)
803 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(minor)
804 return UINT2NUM(minor(get_stat(self
)->st_rdev
));
812 * stat.size -> integer
814 * Returns the size of <i>stat</i> in bytes.
816 * File.stat("testfile").size #=> 66
820 rb_stat_size(VALUE self
)
822 return OFFT2NUM(get_stat(self
)->st_size
);
827 * stat.blksize -> integer or nil
829 * Returns the native file system's block size. Will return <code>nil</code>
830 * on platforms that don't support this information.
832 * File.stat("testfile").blksize #=> 4096
837 rb_stat_blksize(VALUE self
)
839 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
840 return ULONG2NUM(get_stat(self
)->st_blksize
);
848 * stat.blocks -> integer or nil
850 * Returns the number of native file system blocks allocated for this
851 * file, or <code>nil</code> if the operating system doesn't
852 * support this feature.
854 * File.stat("testfile").blocks #=> 2
858 rb_stat_blocks(VALUE self
)
860 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
861 # if SIZEOF_STRUCT_STAT_ST_BLOCKS > SIZEOF_LONG
862 return ULL2NUM(get_stat(self
)->st_blocks
);
864 return ULONG2NUM(get_stat(self
)->st_blocks
);
871 static struct timespec
872 stat_atimespec(const struct stat
*st
)
875 ts
.tv_sec
= st
->st_atime
;
876 #if defined(HAVE_STRUCT_STAT_ST_ATIM)
877 ts
.tv_nsec
= st
->st_atim
.tv_nsec
;
878 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
879 ts
.tv_nsec
= st
->st_atimespec
.tv_nsec
;
880 #elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
881 ts
.tv_nsec
= (long)st
->st_atimensec
;
889 stat_time(const struct timespec ts
)
891 return rb_time_nano_new(ts
.tv_sec
, ts
.tv_nsec
);
895 stat_atime(const struct stat
*st
)
897 return stat_time(stat_atimespec(st
));
900 static struct timespec
901 stat_mtimespec(const struct stat
*st
)
904 ts
.tv_sec
= st
->st_mtime
;
905 #if defined(HAVE_STRUCT_STAT_ST_MTIM)
906 ts
.tv_nsec
= st
->st_mtim
.tv_nsec
;
907 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
908 ts
.tv_nsec
= st
->st_mtimespec
.tv_nsec
;
909 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
910 ts
.tv_nsec
= (long)st
->st_mtimensec
;
918 stat_mtime(const struct stat
*st
)
920 return stat_time(stat_mtimespec(st
));
923 static struct timespec
924 stat_ctimespec(const struct stat
*st
)
927 ts
.tv_sec
= st
->st_ctime
;
928 #if defined(HAVE_STRUCT_STAT_ST_CTIM)
929 ts
.tv_nsec
= st
->st_ctim
.tv_nsec
;
930 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
931 ts
.tv_nsec
= st
->st_ctimespec
.tv_nsec
;
932 #elif defined(HAVE_STRUCT_STAT_ST_CTIMENSEC)
933 ts
.tv_nsec
= (long)st
->st_ctimensec
;
941 stat_ctime(const struct stat
*st
)
943 return stat_time(stat_ctimespec(st
));
946 #define HAVE_STAT_BIRTHTIME
947 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
948 typedef struct stat statx_data
;
950 stat_birthtime(const struct stat
*st
)
952 const struct timespec
*ts
= &st
->st_birthtimespec
;
953 return rb_time_nano_new(ts
->tv_sec
, ts
->tv_nsec
);
955 #elif defined(_WIN32)
956 typedef struct stat statx_data
;
957 # define stat_birthtime stat_ctime
959 # undef HAVE_STAT_BIRTHTIME
966 * Returns the last access time for this file as an object of class
969 * File.stat("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
974 rb_stat_atime(VALUE self
)
976 return stat_atime(get_stat(self
));
981 * stat.mtime -> aTime
983 * Returns the modification time of <i>stat</i>.
985 * File.stat("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
990 rb_stat_mtime(VALUE self
)
992 return stat_mtime(get_stat(self
));
997 * stat.ctime -> aTime
999 * Returns the change time for <i>stat</i> (that is, the time
1000 * directory information about the file was changed, not the file
1003 * Note that on Windows (NTFS), returns creation time (birth time).
1005 * File.stat("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
1010 rb_stat_ctime(VALUE self
)
1012 return stat_ctime(get_stat(self
));
1015 #if defined(HAVE_STAT_BIRTHTIME)
1018 * stat.birthtime -> aTime
1020 * Returns the birth time for <i>stat</i>.
1022 * If the platform doesn't have birthtime, raises NotImplementedError.
1024 * File.write("testfile", "foo")
1026 * File.write("testfile", "bar")
1028 * File.chmod(0644, "testfile")
1030 * File.read("testfile")
1031 * File.stat("testfile").birthtime #=> 2014-02-24 11:19:17 +0900
1032 * File.stat("testfile").mtime #=> 2014-02-24 11:19:27 +0900
1033 * File.stat("testfile").ctime #=> 2014-02-24 11:19:37 +0900
1034 * File.stat("testfile").atime #=> 2014-02-24 11:19:47 +0900
1039 rb_stat_birthtime(VALUE self
)
1041 return stat_birthtime(get_stat(self
));
1044 # define rb_stat_birthtime rb_f_notimplement
1049 * stat.inspect -> string
1051 * Produce a nicely formatted description of <i>stat</i>.
1053 * File.stat("/etc/passwd").inspect
1054 * #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
1055 * # nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
1056 * # blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
1057 * # mtime=Fri Sep 12 15:41:41 CDT 2003,
1058 * # ctime=Mon Oct 27 11:20:27 CST 2003,
1059 * # birthtime=Mon Aug 04 08:13:49 CDT 2003>"
1063 rb_stat_inspect(VALUE self
)
1067 static const struct {
1069 VALUE (*func
)(VALUE
);
1071 {"dev", rb_stat_dev
},
1072 {"ino", rb_stat_ino
},
1073 {"mode", rb_stat_mode
},
1074 {"nlink", rb_stat_nlink
},
1075 {"uid", rb_stat_uid
},
1076 {"gid", rb_stat_gid
},
1077 {"rdev", rb_stat_rdev
},
1078 {"size", rb_stat_size
},
1079 {"blksize", rb_stat_blksize
},
1080 {"blocks", rb_stat_blocks
},
1081 {"atime", rb_stat_atime
},
1082 {"mtime", rb_stat_mtime
},
1083 {"ctime", rb_stat_ctime
},
1084 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1085 {"birthtime", rb_stat_birthtime
},
1090 TypedData_Get_Struct(self
, struct stat
, &stat_data_type
, st
);
1092 return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self
));
1095 str
= rb_str_buf_new2("#<");
1096 rb_str_buf_cat2(str
, rb_obj_classname(self
));
1097 rb_str_buf_cat2(str
, " ");
1099 for (i
= 0; i
< sizeof(member
)/sizeof(member
[0]); i
++) {
1103 rb_str_buf_cat2(str
, ", ");
1105 rb_str_buf_cat2(str
, member
[i
].name
);
1106 rb_str_buf_cat2(str
, "=");
1107 v
= (*member
[i
].func
)(self
);
1108 if (i
== 2) { /* mode */
1109 rb_str_catf(str
, "0%lo", (unsigned long)NUM2ULONG(v
));
1111 else if (i
== 0 || i
== 6) { /* dev/rdev */
1112 rb_str_catf(str
, "0x%"PRI_DEVT_PREFIX
"x", NUM2DEVT(v
));
1115 rb_str_append(str
, rb_inspect(v
));
1118 rb_str_buf_cat2(str
, ">");
1123 typedef struct no_gvl_stat_data
{
1132 no_gvl_fstat(void *data
)
1134 no_gvl_stat_data
*arg
= data
;
1135 return (VALUE
)fstat(arg
->file
.fd
, arg
->st
);
1139 fstat_without_gvl(int fd
, struct stat
*st
)
1141 no_gvl_stat_data data
;
1146 return (int)(VALUE
)rb_thread_io_blocking_region(no_gvl_fstat
, &data
, fd
);
1150 no_gvl_stat(void * data
)
1152 no_gvl_stat_data
*arg
= data
;
1153 return (void *)(VALUE
)STAT(arg
->file
.path
, arg
->st
);
1157 stat_without_gvl(const char *path
, struct stat
*st
)
1159 no_gvl_stat_data data
;
1161 data
.file
.path
= path
;
1164 return (int)(VALUE
)rb_thread_call_without_gvl(no_gvl_stat
, &data
,
1168 #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1169 defined(HAVE_STRUCT_STATX_STX_BTIME)
1172 # ifdef HAVE_SYSCALL_H
1173 # include <syscall.h>
1174 # elif defined HAVE_SYS_SYSCALL_H
1175 # include <sys/syscall.h>
1177 # if defined __linux__
1178 # include <linux/stat.h>
1180 statx(int dirfd
, const char *pathname
, int flags
,
1181 unsigned int mask
, struct statx
*statxbuf
)
1183 return (int)syscall(__NR_statx
, dirfd
, pathname
, flags
, mask
, statxbuf
);
1188 typedef struct no_gvl_statx_data
{
1194 } no_gvl_statx_data
;
1197 io_blocking_statx(void *data
)
1199 no_gvl_statx_data
*arg
= data
;
1200 return (VALUE
)statx(arg
->fd
, arg
->path
, arg
->flags
, arg
->mask
, arg
->stx
);
1204 no_gvl_statx(void *data
)
1206 return (void *)io_blocking_statx(data
);
1210 statx_without_gvl(const char *path
, struct statx
*stx
, unsigned int mask
)
1212 no_gvl_statx_data data
= {stx
, AT_FDCWD
, path
, 0, mask
};
1214 /* call statx(2) with pathname */
1215 return (int)(VALUE
)rb_thread_call_without_gvl(no_gvl_statx
, &data
,
1220 fstatx_without_gvl(int fd
, struct statx
*stx
, unsigned int mask
)
1222 no_gvl_statx_data data
= {stx
, fd
, "", AT_EMPTY_PATH
, mask
};
1224 /* call statx(2) with fd */
1225 return (int)rb_thread_io_blocking_region(io_blocking_statx
, &data
, fd
);
1229 rb_statx(VALUE file
, struct statx
*stx
, unsigned int mask
)
1234 tmp
= rb_check_convert_type_with_id(file
, T_FILE
, "IO", idTo_io
);
1237 GetOpenFile(tmp
, fptr
);
1238 result
= fstatx_without_gvl(fptr
->fd
, stx
, mask
);
1242 FilePathValue(file
);
1243 file
= rb_str_encode_ospath(file
);
1244 result
= statx_without_gvl(RSTRING_PTR(file
), stx
, mask
);
1250 # define statx_has_birthtime(st) ((st)->stx_mask & STATX_BTIME)
1252 NORETURN(static void statx_notimplement(const char *field_name
));
1254 /* rb_notimplement() shows "function is unimplemented on this machine".
1255 It is not applicable to statx which behavior depends on the filesystem. */
1257 statx_notimplement(const char *field_name
)
1259 rb_raise(rb_eNotImpError
,
1260 "%s is unimplemented on this filesystem",
1265 statx_birthtime(const struct statx
*stx
, VALUE fname
)
1267 if (!statx_has_birthtime(stx
)) {
1268 /* birthtime is not supported on the filesystem */
1269 statx_notimplement("birthtime");
1271 return rb_time_nano_new((time_t)stx
->stx_btime
.tv_sec
, stx
->stx_btime
.tv_nsec
);
1274 typedef struct statx statx_data
;
1275 # define HAVE_STAT_BIRTHTIME
1277 #elif defined(HAVE_STAT_BIRTHTIME)
1278 # define statx_without_gvl(path, st, mask) stat_without_gvl(path, st)
1279 # define fstatx_without_gvl(fd, st, mask) fstat_without_gvl(fd, st)
1280 # define statx_birthtime(st, fname) stat_birthtime(st)
1281 # define statx_has_birthtime(st) 1
1282 # define rb_statx(file, st, mask) rb_stat(file, st)
1284 # define statx_has_birthtime(st) 0
1288 rb_stat(VALUE file
, struct stat
*st
)
1293 tmp
= rb_check_convert_type_with_id(file
, T_FILE
, "IO", idTo_io
);
1297 GetOpenFile(tmp
, fptr
);
1298 result
= fstat_without_gvl(fptr
->fd
, st
);
1302 FilePathValue(file
);
1303 file
= rb_str_encode_ospath(file
);
1304 result
= stat_without_gvl(RSTRING_PTR(file
), st
);
1312 * File.stat(file_name) -> stat
1314 * Returns a File::Stat object for the named file (see File::Stat).
1316 * File.stat("testfile").mtime #=> Tue Apr 08 12:58:04 CDT 2003
1321 rb_file_s_stat(VALUE klass
, VALUE fname
)
1325 FilePathValue(fname
);
1326 fname
= rb_str_encode_ospath(fname
);
1327 if (stat_without_gvl(RSTRING_PTR(fname
), &st
) < 0) {
1328 rb_sys_fail_path(fname
);
1330 return rb_stat_new(&st
);
1337 * Returns status information for <em>ios</em> as an object of type
1340 * f = File.new("testfile")
1342 * "%o" % s.mode #=> "100644"
1343 * s.blksize #=> 4096
1344 * s.atime #=> Wed Apr 09 08:53:54 CDT 2003
1349 rb_io_stat(VALUE obj
)
1354 GetOpenFile(obj
, fptr
);
1355 if (fstat(fptr
->fd
, &st
) == -1) {
1356 rb_sys_fail_path(fptr
->pathv
);
1358 return rb_stat_new(&st
);
1363 no_gvl_lstat(void *ptr
)
1365 no_gvl_stat_data
*arg
= ptr
;
1366 return (void *)(VALUE
)lstat(arg
->file
.path
, arg
->st
);
1370 lstat_without_gvl(const char *path
, struct stat
*st
)
1372 no_gvl_stat_data data
;
1374 data
.file
.path
= path
;
1377 return (int)(VALUE
)rb_thread_call_without_gvl(no_gvl_lstat
, &data
,
1380 #endif /* HAVE_LSTAT */
1384 * File.lstat(file_name) -> stat
1386 * Same as File::stat, but does not follow the last symbolic link.
1387 * Instead, reports on the link itself.
1389 * File.symlink("testfile", "link2test") #=> 0
1390 * File.stat("testfile").size #=> 66
1391 * File.lstat("link2test").size #=> 8
1392 * File.stat("link2test").size #=> 66
1397 rb_file_s_lstat(VALUE klass
, VALUE fname
)
1402 FilePathValue(fname
);
1403 fname
= rb_str_encode_ospath(fname
);
1404 if (lstat_without_gvl(StringValueCStr(fname
), &st
) == -1) {
1405 rb_sys_fail_path(fname
);
1407 return rb_stat_new(&st
);
1409 return rb_file_s_stat(klass
, fname
);
1415 * file.lstat -> stat
1417 * Same as IO#stat, but does not follow the last symbolic link.
1418 * Instead, reports on the link itself.
1420 * File.symlink("testfile", "link2test") #=> 0
1421 * File.stat("testfile").size #=> 66
1422 * f = File.new("link2test")
1423 * f.lstat.size #=> 8
1424 * f.stat.size #=> 66
1428 rb_file_lstat(VALUE obj
)
1435 GetOpenFile(obj
, fptr
);
1436 if (NIL_P(fptr
->pathv
)) return Qnil
;
1437 path
= rb_str_encode_ospath(fptr
->pathv
);
1438 if (lstat_without_gvl(RSTRING_PTR(path
), &st
) == -1) {
1439 rb_sys_fail_path(fptr
->pathv
);
1441 return rb_stat_new(&st
);
1443 return rb_io_stat(obj
);
1448 rb_group_member(GETGROUPS_T gid
)
1450 #if defined(_WIN32) || !defined(HAVE_GETGROUPS)
1459 if (getgid() == gid
|| getegid() == gid
)
1462 groups
= getgroups(0, NULL
);
1463 gary
= ALLOCV_N(GETGROUPS_T
, v
, groups
);
1464 anum
= getgroups(groups
, gary
);
1465 while (--anum
>= 0) {
1466 if (gary
[anum
] == gid
) {
1479 # define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
1482 #if defined(S_IXGRP) && !defined(_WIN32) && !defined(__CYGWIN__)
1483 #define USE_GETEUID 1
1486 #ifndef HAVE_EACCESS
1488 eaccess(const char *path
, int mode
)
1496 /* no setuid nor setgid. run shortcut. */
1497 if (getuid() == euid
&& getgid() == getegid())
1498 return access(path
, mode
);
1500 if (STAT(path
, &st
) < 0)
1504 /* Root can read or write any file. */
1508 /* Root can execute any file that has any one of the execute
1510 if (st
.st_mode
& S_IXUGO
)
1516 if (st
.st_uid
== euid
) /* owner */
1518 else if (rb_group_member(st
.st_gid
))
1521 if ((int)(st
.st_mode
& mode
) == mode
) return 0;
1525 return access(path
, mode
);
1536 nogvl_eaccess(void *ptr
)
1538 struct access_arg
*aa
= ptr
;
1540 return (void *)(VALUE
)eaccess(aa
->path
, aa
->mode
);
1544 rb_eaccess(VALUE fname
, int mode
)
1546 struct access_arg aa
;
1548 FilePathValue(fname
);
1549 fname
= rb_str_encode_ospath(fname
);
1550 aa
.path
= StringValueCStr(fname
);
1553 return (int)(VALUE
)rb_thread_call_without_gvl(nogvl_eaccess
, &aa
,
1558 nogvl_access(void *ptr
)
1560 struct access_arg
*aa
= ptr
;
1562 return (void *)(VALUE
)access(aa
->path
, aa
->mode
);
1566 rb_access(VALUE fname
, int mode
)
1568 struct access_arg aa
;
1570 FilePathValue(fname
);
1571 fname
= rb_str_encode_ospath(fname
);
1572 aa
.path
= StringValueCStr(fname
);
1575 return (int)(VALUE
)rb_thread_call_without_gvl(nogvl_access
, &aa
,
1580 * Document-class: FileTest
1582 * FileTest implements file test operations similar to those used in
1583 * File::Stat. It exists as a standalone module, and its methods are
1584 * also insinuated into the File class. (Note that this is not done
1585 * by inclusion: the interpreter cheats).
1590 * Document-method: directory?
1593 * File.directory?(file_name) -> true or false
1595 * Returns <code>true</code> if the named file is a directory,
1596 * or a symlink that points at a directory, and <code>false</code>
1599 * _file_name_ can be an IO object.
1601 * File.directory?(".")
1605 rb_file_directory_p(VALUE obj
, VALUE fname
)
1608 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1613 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1614 if (S_ISDIR(st
.st_mode
)) return Qtrue
;
1620 * File.pipe?(file_name) -> true or false
1622 * Returns <code>true</code> if the named file is a pipe.
1624 * _file_name_ can be an IO object.
1628 rb_file_pipe_p(VALUE obj
, VALUE fname
)
1632 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
1637 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1638 if (S_ISFIFO(st
.st_mode
)) return Qtrue
;
1646 * File.symlink?(file_name) -> true or false
1648 * Returns <code>true</code> if the named file is a symbolic link.
1652 rb_file_symlink_p(VALUE obj
, VALUE fname
)
1656 # define S_ISLNK(m) _S_ISLNK(m)
1659 # define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
1662 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
1671 FilePathValue(fname
);
1672 fname
= rb_str_encode_ospath(fname
);
1673 if (lstat_without_gvl(StringValueCStr(fname
), &st
) < 0) return Qfalse
;
1674 if (S_ISLNK(st
.st_mode
)) return Qtrue
;
1682 * File.socket?(file_name) -> true or false
1684 * Returns <code>true</code> if the named file is a socket.
1686 * _file_name_ can be an IO object.
1690 rb_file_socket_p(VALUE obj
, VALUE fname
)
1694 # define S_ISSOCK(m) _S_ISSOCK(m)
1697 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
1700 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
1709 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1710 if (S_ISSOCK(st
.st_mode
)) return Qtrue
;
1718 * File.blockdev?(file_name) -> true or false
1720 * Returns <code>true</code> if the named file is a block device.
1722 * _file_name_ can be an IO object.
1726 rb_file_blockdev_p(VALUE obj
, VALUE fname
)
1730 # define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
1732 # define S_ISBLK(m) (0) /* anytime false */
1739 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1740 if (S_ISBLK(st
.st_mode
)) return Qtrue
;
1748 * File.chardev?(file_name) -> true or false
1750 * Returns <code>true</code> if the named file is a character device.
1752 * _file_name_ can be an IO object.
1755 rb_file_chardev_p(VALUE obj
, VALUE fname
)
1758 # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
1763 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1764 if (S_ISCHR(st
.st_mode
)) return Qtrue
;
1771 * File.exist?(file_name) -> true or false
1773 * Return <code>true</code> if the named file exists.
1775 * _file_name_ can be an IO object.
1777 * "file exists" means that stat() or fstat() system call is successful.
1781 rb_file_exist_p(VALUE obj
, VALUE fname
)
1785 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1791 * File.readable?(file_name) -> true or false
1793 * Returns <code>true</code> if the named file is readable by the effective
1794 * user and group id of this process. See eaccess(3).
1796 * Note that some OS-level security features may cause this to return true
1797 * even though the file is not readable by the effective user/group.
1801 rb_file_readable_p(VALUE obj
, VALUE fname
)
1803 return RBOOL(rb_eaccess(fname
, R_OK
) >= 0);
1808 * File.readable_real?(file_name) -> true or false
1810 * Returns <code>true</code> if the named file is readable by the real
1811 * user and group id of this process. See access(3).
1813 * Note that some OS-level security features may cause this to return true
1814 * even though the file is not readable by the real user/group.
1818 rb_file_readable_real_p(VALUE obj
, VALUE fname
)
1820 return RBOOL(rb_access(fname
, R_OK
) >= 0);
1824 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1828 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
1833 * File.world_readable?(file_name) -> integer or nil
1835 * If <i>file_name</i> is readable by others, returns an integer
1836 * representing the file permission bits of <i>file_name</i>. Returns
1837 * <code>nil</code> otherwise. The meaning of the bits is platform
1838 * dependent; on Unix systems, see <code>stat(2)</code>.
1840 * _file_name_ can be an IO object.
1842 * File.world_readable?("/etc/passwd") #=> 420
1843 * m = File.world_readable?("/etc/passwd")
1844 * sprintf("%o", m) #=> "644"
1848 rb_file_world_readable_p(VALUE obj
, VALUE fname
)
1853 if (rb_stat(fname
, &st
) < 0) return Qnil
;
1854 if ((st
.st_mode
& (S_IROTH
)) == S_IROTH
) {
1855 return UINT2NUM(st
.st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
1863 * File.writable?(file_name) -> true or false
1865 * Returns <code>true</code> if the named file is writable by the effective
1866 * user and group id of this process. See eaccess(3).
1868 * Note that some OS-level security features may cause this to return true
1869 * even though the file is not writable by the effective user/group.
1873 rb_file_writable_p(VALUE obj
, VALUE fname
)
1875 return RBOOL(rb_eaccess(fname
, W_OK
) >= 0);
1880 * File.writable_real?(file_name) -> true or false
1882 * Returns <code>true</code> if the named file is writable by the real
1883 * user and group id of this process. See access(3).
1885 * Note that some OS-level security features may cause this to return true
1886 * even though the file is not writable by the real user/group.
1890 rb_file_writable_real_p(VALUE obj
, VALUE fname
)
1892 return RBOOL(rb_access(fname
, W_OK
) >= 0);
1897 * File.world_writable?(file_name) -> integer or nil
1899 * If <i>file_name</i> is writable by others, returns an integer
1900 * representing the file permission bits of <i>file_name</i>. Returns
1901 * <code>nil</code> otherwise. The meaning of the bits is platform
1902 * dependent; on Unix systems, see <code>stat(2)</code>.
1904 * _file_name_ can be an IO object.
1906 * File.world_writable?("/tmp") #=> 511
1907 * m = File.world_writable?("/tmp")
1908 * sprintf("%o", m) #=> "777"
1912 rb_file_world_writable_p(VALUE obj
, VALUE fname
)
1917 if (rb_stat(fname
, &st
) < 0) return Qnil
;
1918 if ((st
.st_mode
& (S_IWOTH
)) == S_IWOTH
) {
1919 return UINT2NUM(st
.st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
1927 * File.executable?(file_name) -> true or false
1929 * Returns <code>true</code> if the named file is executable by the effective
1930 * user and group id of this process. See eaccess(3).
1932 * Windows does not support execute permissions separately from read
1933 * permissions. On Windows, a file is only considered executable if it ends in
1934 * .bat, .cmd, .com, or .exe.
1936 * Note that some OS-level security features may cause this to return true
1937 * even though the file is not executable by the effective user/group.
1941 rb_file_executable_p(VALUE obj
, VALUE fname
)
1943 return RBOOL(rb_eaccess(fname
, X_OK
) >= 0);
1948 * File.executable_real?(file_name) -> true or false
1950 * Returns <code>true</code> if the named file is executable by the real
1951 * user and group id of this process. See access(3).
1953 * Windows does not support execute permissions separately from read
1954 * permissions. On Windows, a file is only considered executable if it ends in
1955 * .bat, .cmd, .com, or .exe.
1957 * Note that some OS-level security features may cause this to return true
1958 * even though the file is not executable by the real user/group.
1962 rb_file_executable_real_p(VALUE obj
, VALUE fname
)
1964 return RBOOL(rb_access(fname
, X_OK
) >= 0);
1968 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1973 * File.file?(file) -> true or false
1975 * Returns +true+ if the named +file+ exists and is a regular file.
1977 * +file+ can be an IO object.
1979 * If the +file+ argument is a symbolic link, it will resolve the symbolic link
1980 * and use the file referenced by the link.
1984 rb_file_file_p(VALUE obj
, VALUE fname
)
1988 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
1989 return RBOOL(S_ISREG(st
.st_mode
));
1994 * File.zero?(file_name) -> true or false
1996 * Returns <code>true</code> if the named file exists and has
1999 * _file_name_ can be an IO object.
2003 rb_file_zero_p(VALUE obj
, VALUE fname
)
2007 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2008 return RBOOL(st
.st_size
== 0);
2013 * File.size?(file_name) -> Integer or nil
2015 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
2018 * _file_name_ can be an IO object.
2022 rb_file_size_p(VALUE obj
, VALUE fname
)
2026 if (rb_stat(fname
, &st
) < 0) return Qnil
;
2027 if (st
.st_size
== 0) return Qnil
;
2028 return OFFT2NUM(st
.st_size
);
2033 * File.owned?(file_name) -> true or false
2035 * Returns <code>true</code> if the named file exists and the
2036 * effective used id of the calling process is the owner of
2039 * _file_name_ can be an IO object.
2043 rb_file_owned_p(VALUE obj
, VALUE fname
)
2047 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2048 return RBOOL(st
.st_uid
== geteuid());
2052 rb_file_rowned_p(VALUE obj
, VALUE fname
)
2056 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2057 return RBOOL(st
.st_uid
== getuid());
2062 * File.grpowned?(file_name) -> true or false
2064 * Returns <code>true</code> if the named file exists and the
2065 * effective group id of the calling process is the owner of
2066 * the file. Returns <code>false</code> on Windows.
2068 * _file_name_ can be an IO object.
2072 rb_file_grpowned_p(VALUE obj
, VALUE fname
)
2077 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2078 if (rb_group_member(st
.st_gid
)) return Qtrue
;
2083 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2085 check3rdbyte(VALUE fname
, int mode
)
2089 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2090 return RBOOL(st
.st_mode
& mode
);
2096 * File.setuid?(file_name) -> true or false
2098 * Returns <code>true</code> if the named file has the setuid bit set.
2100 * _file_name_ can be an IO object.
2104 rb_file_suid_p(VALUE obj
, VALUE fname
)
2107 return check3rdbyte(fname
, S_ISUID
);
2115 * File.setgid?(file_name) -> true or false
2117 * Returns <code>true</code> if the named file has the setgid bit set.
2119 * _file_name_ can be an IO object.
2123 rb_file_sgid_p(VALUE obj
, VALUE fname
)
2126 return check3rdbyte(fname
, S_ISGID
);
2134 * File.sticky?(file_name) -> true or false
2136 * Returns <code>true</code> if the named file has the sticky bit set.
2138 * _file_name_ can be an IO object.
2142 rb_file_sticky_p(VALUE obj
, VALUE fname
)
2145 return check3rdbyte(fname
, S_ISVTX
);
2153 * File.identical?(file_1, file_2) -> true or false
2155 * Returns <code>true</code> if the named files are identical.
2157 * _file_1_ and _file_2_ can be an IO object.
2160 * p File.identical?("a", "a") #=> true
2161 * p File.identical?("a", "./a") #=> true
2162 * File.link("a", "b")
2163 * p File.identical?("a", "b") #=> true
2164 * File.symlink("a", "c")
2165 * p File.identical?("a", "c") #=> true
2167 * p File.identical?("a", "d") #=> false
2171 rb_file_identical_p(VALUE obj
, VALUE fname1
, VALUE fname2
)
2174 struct stat st1
, st2
;
2176 if (rb_stat(fname1
, &st1
) < 0) return Qfalse
;
2177 if (rb_stat(fname2
, &st2
) < 0) return Qfalse
;
2178 if (st1
.st_dev
!= st2
.st_dev
) return Qfalse
;
2179 if (st1
.st_ino
!= st2
.st_ino
) return Qfalse
;
2182 extern VALUE
rb_w32_file_identical_p(VALUE
, VALUE
);
2183 return rb_w32_file_identical_p(fname1
, fname2
);
2189 * File.size(file_name) -> integer
2191 * Returns the size of <code>file_name</code>.
2193 * _file_name_ can be an IO object.
2197 rb_file_s_size(VALUE klass
, VALUE fname
)
2201 if (rb_stat(fname
, &st
) < 0) {
2203 FilePathValue(fname
);
2204 rb_syserr_fail_path(e
, fname
);
2206 return OFFT2NUM(st
.st_size
);
2210 rb_file_ftype(const struct stat
*st
)
2214 if (S_ISREG(st
->st_mode
)) {
2217 else if (S_ISDIR(st
->st_mode
)) {
2220 else if (S_ISCHR(st
->st_mode
)) {
2221 t
= "characterSpecial";
2224 else if (S_ISBLK(st
->st_mode
)) {
2229 else if (S_ISFIFO(st
->st_mode
)) {
2234 else if (S_ISLNK(st
->st_mode
)) {
2239 else if (S_ISSOCK(st
->st_mode
)) {
2247 return rb_usascii_str_new2(t
);
2252 * File.ftype(file_name) -> string
2254 * Identifies the type of the named file; the return string is one of
2255 * ``<code>file</code>'', ``<code>directory</code>'',
2256 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
2257 * ``<code>fifo</code>'', ``<code>link</code>'',
2258 * ``<code>socket</code>'', or ``<code>unknown</code>''.
2260 * File.ftype("testfile") #=> "file"
2261 * File.ftype("/dev/tty") #=> "characterSpecial"
2262 * File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2266 rb_file_s_ftype(VALUE klass
, VALUE fname
)
2270 FilePathValue(fname
);
2271 fname
= rb_str_encode_ospath(fname
);
2272 if (lstat_without_gvl(StringValueCStr(fname
), &st
) == -1) {
2273 rb_sys_fail_path(fname
);
2276 return rb_file_ftype(&st
);
2281 * File.atime(file_name) -> time
2283 * Returns the last access time for the named file as a Time object.
2285 * _file_name_ can be an IO object.
2287 * File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2292 rb_file_s_atime(VALUE klass
, VALUE fname
)
2296 if (rb_stat(fname
, &st
) < 0) {
2298 FilePathValue(fname
);
2299 rb_syserr_fail_path(e
, fname
);
2301 return stat_atime(&st
);
2306 * file.atime -> time
2308 * Returns the last access time (a Time object) for <i>file</i>, or
2309 * epoch if <i>file</i> has not been accessed.
2311 * File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2316 rb_file_atime(VALUE obj
)
2321 GetOpenFile(obj
, fptr
);
2322 if (fstat(fptr
->fd
, &st
) == -1) {
2323 rb_sys_fail_path(fptr
->pathv
);
2325 return stat_atime(&st
);
2330 * File.mtime(file_name) -> time
2332 * Returns the modification time for the named file as a Time object.
2334 * _file_name_ can be an IO object.
2336 * File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2341 rb_file_s_mtime(VALUE klass
, VALUE fname
)
2345 if (rb_stat(fname
, &st
) < 0) {
2347 FilePathValue(fname
);
2348 rb_syserr_fail_path(e
, fname
);
2350 return stat_mtime(&st
);
2355 * file.mtime -> time
2357 * Returns the modification time for <i>file</i>.
2359 * File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2364 rb_file_mtime(VALUE obj
)
2369 GetOpenFile(obj
, fptr
);
2370 if (fstat(fptr
->fd
, &st
) == -1) {
2371 rb_sys_fail_path(fptr
->pathv
);
2373 return stat_mtime(&st
);
2378 * File.ctime(file_name) -> time
2380 * Returns the change time for the named file (the time at which
2381 * directory information about the file was changed, not the file
2384 * _file_name_ can be an IO object.
2386 * Note that on Windows (NTFS), returns creation time (birth time).
2388 * File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2393 rb_file_s_ctime(VALUE klass
, VALUE fname
)
2397 if (rb_stat(fname
, &st
) < 0) {
2399 FilePathValue(fname
);
2400 rb_syserr_fail_path(e
, fname
);
2402 return stat_ctime(&st
);
2407 * file.ctime -> time
2409 * Returns the change time for <i>file</i> (that is, the time directory
2410 * information about the file was changed, not the file itself).
2412 * Note that on Windows (NTFS), returns creation time (birth time).
2414 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2419 rb_file_ctime(VALUE obj
)
2424 GetOpenFile(obj
, fptr
);
2425 if (fstat(fptr
->fd
, &st
) == -1) {
2426 rb_sys_fail_path(fptr
->pathv
);
2428 return stat_ctime(&st
);
2433 * File.birthtime(file_name) -> time
2435 * Returns the birth time for the named file.
2437 * _file_name_ can be an IO object.
2439 * File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2441 * If the platform doesn't have birthtime, raises NotImplementedError.
2445 #if defined(HAVE_STAT_BIRTHTIME)
2446 RUBY_FUNC_EXPORTED VALUE
2447 rb_file_s_birthtime(VALUE klass
, VALUE fname
)
2451 if (rb_statx(fname
, &st
, STATX_BTIME
) < 0) {
2453 FilePathValue(fname
);
2454 rb_syserr_fail_path(e
, fname
);
2456 return statx_birthtime(&st
, fname
);
2459 # define rb_file_s_birthtime rb_f_notimplement
2462 #if defined(HAVE_STAT_BIRTHTIME)
2465 * file.birthtime -> time
2467 * Returns the birth time for <i>file</i>.
2469 * File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
2471 * If the platform doesn't have birthtime, raises NotImplementedError.
2476 rb_file_birthtime(VALUE obj
)
2481 GetOpenFile(obj
, fptr
);
2482 if (fstatx_without_gvl(fptr
->fd
, &st
, STATX_BTIME
) == -1) {
2483 rb_sys_fail_path(fptr
->pathv
);
2485 return statx_birthtime(&st
, fptr
->pathv
);
2488 # define rb_file_birthtime rb_f_notimplement
2493 * file.size -> integer
2495 * Returns the size of <i>file</i> in bytes.
2497 * File.new("testfile").size #=> 66
2502 rb_file_size(VALUE file
)
2504 if (RB_TYPE_P(file
, T_FILE
)) {
2508 RB_IO_POINTER(file
, fptr
);
2509 if (fptr
->mode
& FMODE_WRITABLE
) {
2510 rb_io_flush_raw(file
, 0);
2513 if (fstat(fptr
->fd
, &st
) == -1) {
2514 rb_sys_fail_path(fptr
->pathv
);
2520 return NUM2OFFT(rb_funcall(file
, idSize
, 0));
2525 file_size(VALUE self
)
2527 return OFFT2NUM(rb_file_size(self
));
2531 chmod_internal(const char *path
, void *mode
)
2533 return chmod(path
, *(mode_t
*)mode
);
2538 * File.chmod(mode_int, file_name, ... ) -> integer
2540 * Changes permission bits on the named file(s) to the bit pattern
2541 * represented by <i>mode_int</i>. Actual effects are operating system
2542 * dependent (see the beginning of this section). On Unix systems, see
2543 * <code>chmod(2)</code> for details. Returns the number of files
2546 * File.chmod(0644, "testfile", "out") #=> 2
2550 rb_file_s_chmod(int argc
, VALUE
*argv
, VALUE _
)
2555 mode
= NUM2MODET(*argv
++);
2557 return apply2files(chmod_internal
, argc
, argv
, &mode
);
2562 * file.chmod(mode_int) -> 0
2564 * Changes permission bits on <i>file</i> to the bit pattern
2565 * represented by <i>mode_int</i>. Actual effects are platform
2566 * dependent; on Unix systems, see <code>chmod(2)</code> for details.
2567 * Follows symbolic links. Also see File#lchmod.
2569 * f = File.new("out", "w");
2570 * f.chmod(0644) #=> 0
2574 rb_file_chmod(VALUE obj
, VALUE vmode
)
2578 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2582 mode
= NUM2MODET(vmode
);
2584 GetOpenFile(obj
, fptr
);
2586 if (fchmod(fptr
->fd
, mode
) == -1) {
2587 if (HAVE_FCHMOD
|| errno
!= ENOSYS
)
2588 rb_sys_fail_path(fptr
->pathv
);
2591 if (!HAVE_FCHMOD
) return INT2FIX(0);
2594 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2595 if (NIL_P(fptr
->pathv
)) return Qnil
;
2596 path
= rb_str_encode_ospath(fptr
->pathv
);
2597 if (chmod(RSTRING_PTR(path
), mode
) == -1)
2598 rb_sys_fail_path(fptr
->pathv
);
2604 #if defined(HAVE_LCHMOD)
2606 lchmod_internal(const char *path
, void *mode
)
2608 return lchmod(path
, *(mode_t
*)mode
);
2613 * File.lchmod(mode_int, file_name, ...) -> integer
2615 * Equivalent to File::chmod, but does not follow symbolic links (so
2616 * it will change the permissions associated with the link, not the
2617 * file referenced by the link). Often not available.
2622 rb_file_s_lchmod(int argc
, VALUE
*argv
, VALUE _
)
2627 mode
= NUM2MODET(*argv
++);
2629 return apply2files(lchmod_internal
, argc
, argv
, &mode
);
2632 #define rb_file_s_lchmod rb_f_notimplement
2635 static inline rb_uid_t
2639 return (rb_uid_t
)-1;
2644 static inline rb_gid_t
2648 return (rb_gid_t
)-1;
2659 chown_internal(const char *path
, void *arg
)
2661 struct chown_args
*args
= arg
;
2662 return chown(path
, args
->owner
, args
->group
);
2667 * File.chown(owner_int, group_int, file_name, ...) -> integer
2669 * Changes the owner and group of the named file(s) to the given
2670 * numeric owner and group id's. Only a process with superuser
2671 * privileges may change the owner of a file. The current owner of a
2672 * file may change the file's group to any group to which the owner
2673 * belongs. A <code>nil</code> or -1 owner or group id is ignored.
2674 * Returns the number of files processed.
2676 * File.chown(nil, 100, "testfile")
2681 rb_file_s_chown(int argc
, VALUE
*argv
, VALUE _
)
2683 struct chown_args arg
;
2686 arg
.owner
= to_uid(*argv
++);
2687 arg
.group
= to_gid(*argv
++);
2689 return apply2files(chown_internal
, argc
, argv
, &arg
);
2694 * file.chown(owner_int, group_int ) -> 0
2696 * Changes the owner and group of <i>file</i> to the given numeric
2697 * owner and group id's. Only a process with superuser privileges may
2698 * change the owner of a file. The current owner of a file may change
2699 * the file's group to any group to which the owner belongs. A
2700 * <code>nil</code> or -1 owner or group id is ignored. Follows
2701 * symbolic links. See also File#lchown.
2703 * File.new("testfile").chown(502, 1000)
2708 rb_file_chown(VALUE obj
, VALUE owner
, VALUE group
)
2719 GetOpenFile(obj
, fptr
);
2721 if (NIL_P(fptr
->pathv
)) return Qnil
;
2722 path
= rb_str_encode_ospath(fptr
->pathv
);
2723 if (chown(RSTRING_PTR(path
), o
, g
) == -1)
2724 rb_sys_fail_path(fptr
->pathv
);
2726 if (fchown(fptr
->fd
, o
, g
) == -1)
2727 rb_sys_fail_path(fptr
->pathv
);
2733 #if defined(HAVE_LCHOWN)
2735 lchown_internal(const char *path
, void *arg
)
2737 struct chown_args
*args
= arg
;
2738 return lchown(path
, args
->owner
, args
->group
);
2743 * File.lchown(owner_int, group_int, file_name,..) -> integer
2745 * Equivalent to File::chown, but does not follow symbolic
2746 * links (so it will change the owner associated with the link, not the
2747 * file referenced by the link). Often not available. Returns number
2748 * of files in the argument list.
2753 rb_file_s_lchown(int argc
, VALUE
*argv
, VALUE _
)
2755 struct chown_args arg
;
2758 arg
.owner
= to_uid(*argv
++);
2759 arg
.group
= to_gid(*argv
++);
2761 return apply2files(lchown_internal
, argc
, argv
, &arg
);
2764 #define rb_file_s_lchown rb_f_notimplement
2768 const struct timespec
* tsp
;
2770 int follow
; /* Whether to act on symlinks (1) or their referent (0) */
2774 NORETURN(static void utime_failed(struct apply_arg
*));
2777 utime_failed(struct apply_arg
*aa
)
2780 VALUE path
= aa
->fn
[aa
->i
].path
;
2781 struct utime_args
*ua
= aa
->arg
;
2783 if (ua
->tsp
&& e
== EINVAL
) {
2784 VALUE e
[2], a
= Qnil
, m
= Qnil
;
2786 VALUE atime
= ua
->atime
;
2787 VALUE mtime
= ua
->mtime
;
2789 if (!NIL_P(atime
)) {
2790 a
= rb_inspect(atime
);
2792 if (!NIL_P(mtime
) && mtime
!= atime
&& !rb_equal(atime
, mtime
)) {
2793 m
= rb_inspect(mtime
);
2795 if (NIL_P(a
)) e
[0] = m
;
2796 else if (NIL_P(m
) || rb_str_cmp(a
, m
) == 0) e
[0] = a
;
2798 e
[0] = rb_str_plus(a
, rb_str_new_cstr(" or "));
2799 rb_str_append(e
[0], m
);
2804 if (!d
) e
[0] = rb_str_dup(e
[0]);
2805 rb_str_append(rb_str_cat2(e
[0], " for "), path
);
2807 e
[1] = INT2FIX(EINVAL
);
2808 rb_exc_raise(rb_class_new_instance(2, e
, rb_eSystemCallError
));
2811 rb_syserr_fail_path(e
, path
);
2815 #if defined(HAVE_UTIMES)
2818 utime_internal(const char *path
, void *arg
)
2820 struct utime_args
*v
= arg
;
2821 const struct timespec
*tsp
= v
->tsp
;
2822 struct timeval tvbuf
[2], *tvp
= NULL
;
2824 #if defined(HAVE_UTIMENSAT)
2825 static int try_utimensat
= 1;
2826 # ifdef AT_SYMLINK_NOFOLLOW
2827 static int try_utimensat_follow
= 1;
2829 const int try_utimensat_follow
= 0;
2833 if (v
->follow
? try_utimensat_follow
: try_utimensat
) {
2834 # ifdef AT_SYMLINK_NOFOLLOW
2836 flags
= AT_SYMLINK_NOFOLLOW
;
2840 if (utimensat(AT_FDCWD
, path
, tsp
, flags
) < 0) {
2841 if (errno
== ENOSYS
) {
2842 # ifdef AT_SYMLINK_NOFOLLOW
2843 try_utimensat_follow
= 0;
2849 return -1; /* calls utime_failed */
2857 tvbuf
[0].tv_sec
= tsp
[0].tv_sec
;
2858 tvbuf
[0].tv_usec
= (int)(tsp
[0].tv_nsec
/ 1000);
2859 tvbuf
[1].tv_sec
= tsp
[1].tv_sec
;
2860 tvbuf
[1].tv_usec
= (int)(tsp
[1].tv_nsec
/ 1000);
2864 if (v
->follow
) return lutimes(path
, tvp
);
2866 return utimes(path
, tvp
);
2871 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
2879 utime_internal(const char *path
, void *arg
)
2881 struct utime_args
*v
= arg
;
2882 const struct timespec
*tsp
= v
->tsp
;
2883 struct utimbuf utbuf
, *utp
= NULL
;
2885 utbuf
.actime
= tsp
[0].tv_sec
;
2886 utbuf
.modtime
= tsp
[1].tv_sec
;
2889 return utime(path
, utp
);
2895 utime_internal_i(int argc
, VALUE
*argv
, int follow
)
2897 struct utime_args args
;
2898 struct timespec tss
[2], *tsp
= NULL
;
2901 args
.atime
= *argv
++;
2902 args
.mtime
= *argv
++;
2904 args
.follow
= follow
;
2906 if (!NIL_P(args
.atime
) || !NIL_P(args
.mtime
)) {
2908 tsp
[0] = rb_time_timespec(args
.atime
);
2909 if (args
.atime
== args
.mtime
)
2912 tsp
[1] = rb_time_timespec(args
.mtime
);
2916 return apply2files(utime_internal
, argc
, argv
, &args
);
2921 * File.utime(atime, mtime, file_name, ...) -> integer
2923 * Sets the access and modification times of each named file to the
2924 * first two arguments. If a file is a symlink, this method acts upon
2925 * its referent rather than the link itself; for the inverse
2926 * behavior see File.lutime. Returns the number of file
2927 * names in the argument list.
2931 rb_file_s_utime(int argc
, VALUE
*argv
, VALUE _
)
2933 return utime_internal_i(argc
, argv
, FALSE
);
2936 #if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
2940 * File.lutime(atime, mtime, file_name, ...) -> integer
2942 * Sets the access and modification times of each named file to the
2943 * first two arguments. If a file is a symlink, this method acts upon
2944 * the link itself as opposed to its referent; for the inverse
2945 * behavior, see File.utime. Returns the number of file
2946 * names in the argument list.
2950 rb_file_s_lutime(int argc
, VALUE
*argv
, VALUE _
)
2952 return utime_internal_i(argc
, argv
, TRUE
);
2955 #define rb_file_s_lutime rb_f_notimplement
2958 #ifdef RUBY_FUNCTION_NAME_STRING
2959 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
2961 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
2963 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
2964 NORETURN(static void syserr_fail2_in(const char *,int,VALUE
,VALUE
));
2966 syserr_fail2_in(const char *func
, int e
, VALUE s1
, VALUE s2
)
2970 const int max_pathlen
= MAX_PATH
;
2972 const int max_pathlen
= MAXPATHLEN
;
2976 rb_syserr_fail_path(e
, rb_str_ellipsize(s2
, max_pathlen
));
2978 str
= rb_str_new_cstr("(");
2979 rb_str_append(str
, rb_str_ellipsize(s1
, max_pathlen
));
2980 rb_str_cat2(str
, ", ");
2981 rb_str_append(str
, rb_str_ellipsize(s2
, max_pathlen
));
2982 rb_str_cat2(str
, ")");
2983 #ifdef RUBY_FUNCTION_NAME_STRING
2984 rb_syserr_fail_path_in(func
, e
, str
);
2986 rb_syserr_fail_path(e
, str
);
2993 * File.link(old_name, new_name) -> 0
2995 * Creates a new name for an existing file using a hard link. Will not
2996 * overwrite <i>new_name</i> if it already exists (raising a subclass
2997 * of SystemCallError). Not available on all platforms.
2999 * File.link("testfile", ".testfile") #=> 0
3000 * IO.readlines(".testfile")[0] #=> "This is line one\n"
3004 rb_file_s_link(VALUE klass
, VALUE from
, VALUE to
)
3006 FilePathValue(from
);
3008 from
= rb_str_encode_ospath(from
);
3009 to
= rb_str_encode_ospath(to
);
3011 if (link(StringValueCStr(from
), StringValueCStr(to
)) < 0) {
3012 sys_fail2(from
, to
);
3017 #define rb_file_s_link rb_f_notimplement
3023 * File.symlink(old_name, new_name) -> 0
3025 * Creates a symbolic link called <i>new_name</i> for the existing file
3026 * <i>old_name</i>. Raises a NotImplemented exception on
3027 * platforms that do not support symbolic links.
3029 * File.symlink("testfile", "link2test") #=> 0
3034 rb_file_s_symlink(VALUE klass
, VALUE from
, VALUE to
)
3036 FilePathValue(from
);
3038 from
= rb_str_encode_ospath(from
);
3039 to
= rb_str_encode_ospath(to
);
3041 if (symlink(StringValueCStr(from
), StringValueCStr(to
)) < 0) {
3042 sys_fail2(from
, to
);
3047 #define rb_file_s_symlink rb_f_notimplement
3050 #ifdef HAVE_READLINK
3053 * File.readlink(link_name) -> file_name
3055 * Returns the name of the file referenced by the given link.
3056 * Not available on all platforms.
3058 * File.symlink("testfile", "link2test") #=> 0
3059 * File.readlink("link2test") #=> "testfile"
3063 rb_file_s_readlink(VALUE klass
, VALUE path
)
3065 return rb_readlink(path
, rb_filesystem_encoding());
3069 struct readlink_arg
{
3076 nogvl_readlink(void *ptr
)
3078 struct readlink_arg
*ra
= ptr
;
3080 return (void *)(VALUE
)readlink(ra
->path
, ra
->buf
, ra
->size
);
3084 readlink_without_gvl(VALUE path
, VALUE buf
, size_t size
)
3086 struct readlink_arg ra
;
3088 ra
.path
= RSTRING_PTR(path
);
3089 ra
.buf
= RSTRING_PTR(buf
);
3092 return (ssize_t
)rb_thread_call_without_gvl(nogvl_readlink
, &ra
,
3097 rb_readlink(VALUE path
, rb_encoding
*enc
)
3103 FilePathValue(path
);
3104 path
= rb_str_encode_ospath(path
);
3105 v
= rb_enc_str_new(0, size
, enc
);
3106 while ((rv
= readlink_without_gvl(path
, v
, size
)) == size
3108 || (rv
< 0 && errno
== ERANGE
) /* quirky behavior of GPFS */
3111 rb_str_modify_expand(v
, size
);
3113 rb_str_set_len(v
, size
);
3117 rb_str_resize(v
, 0);
3118 rb_syserr_fail_path(e
, path
);
3120 rb_str_resize(v
, rv
);
3126 #define rb_file_s_readlink rb_f_notimplement
3130 unlink_internal(const char *path
, void *arg
)
3132 return unlink(path
);
3137 * File.delete(file_name, ...) -> integer
3138 * File.unlink(file_name, ...) -> integer
3140 * Deletes the named files, returning the number of names
3141 * passed as arguments. Raises an exception on any error.
3142 * Since the underlying implementation relies on the
3143 * <code>unlink(2)</code> system call, the type of
3144 * exception raised depends on its error type (see
3145 * https://linux.die.net/man/2/unlink) and has the form of
3146 * e.g. Errno::ENOENT.
3148 * See also Dir::rmdir.
3152 rb_file_s_unlink(int argc
, VALUE
*argv
, VALUE klass
)
3154 return apply2files(unlink_internal
, argc
, argv
, 0);
3157 struct rename_args
{
3163 no_gvl_rename(void *ptr
)
3165 struct rename_args
*ra
= ptr
;
3167 return (void *)(VALUE
)rename(ra
->src
, ra
->dst
);
3172 * File.rename(old_name, new_name) -> 0
3174 * Renames the given file to the new name. Raises a SystemCallError
3175 * if the file cannot be renamed.
3177 * File.rename("afile", "afile.bak") #=> 0
3181 rb_file_s_rename(VALUE klass
, VALUE from
, VALUE to
)
3183 struct rename_args ra
;
3186 FilePathValue(from
);
3188 f
= rb_str_encode_ospath(from
);
3189 t
= rb_str_encode_ospath(to
);
3190 ra
.src
= StringValueCStr(f
);
3191 ra
.dst
= StringValueCStr(t
);
3192 #if defined __CYGWIN__
3195 if ((int)(VALUE
)rb_thread_call_without_gvl(no_gvl_rename
, &ra
,
3196 RUBY_UBF_IO
, 0) < 0) {
3201 if (chmod(ra
.dst
, 0666) == 0 &&
3202 unlink(ra
.dst
) == 0 &&
3203 rename(ra
.src
, ra
.dst
) == 0)
3207 syserr_fail2(e
, from
, to
);
3215 * File.umask() -> integer
3216 * File.umask(integer) -> integer
3218 * Returns the current umask value for this process. If the optional
3219 * argument is given, set the umask to that value and return the
3220 * previous value. Umask values are <em>subtracted</em> from the
3221 * default permissions, so a umask of <code>0222</code> would make a
3222 * file read-only for everyone.
3224 * File.umask(0006) #=> 18
3229 rb_file_s_umask(int argc
, VALUE
*argv
, VALUE _
)
3239 omask
= umask(NUM2MODET(argv
[0]));
3242 rb_error_arity(argc
, 0, 1);
3244 return MODET2NUM(omask
);
3250 #if defined __CYGWIN__ || defined DOSISH
3252 #define DOSISH_DRIVE_LETTER
3253 #define FILE_ALT_SEPARATOR '\\'
3255 #ifdef FILE_ALT_SEPARATOR
3256 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3258 static const char file_alt_separator
[] = {FILE_ALT_SEPARATOR
, '\0'};
3261 #define isdirsep(x) ((x) == '/')
3271 #ifndef USE_NTFS_ADS
3273 # define USE_NTFS_ADS 1
3275 # define USE_NTFS_ADS 0
3280 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3282 #define istrailinggarbage(x) 0
3285 # define isADS(x) ((x) == ':')
3290 #define Next(p, e, enc) ((p) + rb_enc_mbclen((p), (e), (enc)))
3291 #define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
3293 #if defined(DOSISH_UNC)
3294 #define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
3296 #define has_unc(buf) 0
3299 #ifdef DOSISH_DRIVE_LETTER
3301 has_drive_letter(const char *buf
)
3303 if (ISALPHA(buf
[0]) && buf
[1] == ':') {
3313 getcwdofdrv(int drv
)
3316 char *drvcwd
, *oldcwd
;
3322 /* the only way that I know to get the current directory
3323 of a particular drive is to change chdir() to that drive,
3324 so save the old cwd before chdir()
3326 oldcwd
= ruby_getcwd();
3327 if (chdir(drive
) == 0) {
3328 drvcwd
= ruby_getcwd();
3333 /* perhaps the drive is not exist. we return only drive letter */
3334 drvcwd
= strdup(drive
);
3340 not_same_drive(VALUE path
, int drive
)
3342 const char *p
= RSTRING_PTR(path
);
3343 if (RSTRING_LEN(path
) < 2) return 0;
3344 if (has_drive_letter(p
)) {
3345 return TOLOWER(p
[0]) != TOLOWER(drive
);
3354 static inline char *
3355 skiproot(const char *path
, const char *end
, rb_encoding
*enc
)
3357 #ifdef DOSISH_DRIVE_LETTER
3358 if (path
+ 2 <= end
&& has_drive_letter(path
)) path
+= 2;
3360 while (path
< end
&& isdirsep(*path
)) path
++;
3361 return (char *)path
;
3364 #define nextdirsep rb_enc_path_next
3366 rb_enc_path_next(const char *s
, const char *e
, rb_encoding
*enc
)
3368 while (s
< e
&& !isdirsep(*s
)) {
3374 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3375 #define skipprefix rb_enc_path_skip_prefix
3377 #define skipprefix(path, end, enc) (path)
3380 rb_enc_path_skip_prefix(const char *path
, const char *end
, rb_encoding
*enc
)
3382 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3384 if (path
+ 2 <= end
&& isdirsep(path
[0]) && isdirsep(path
[1])) {
3386 while (path
< end
&& isdirsep(*path
)) path
++;
3387 if ((path
= rb_enc_path_next(path
, end
, enc
)) < end
&& path
[0] && path
[1] && !isdirsep(path
[1]))
3388 path
= rb_enc_path_next(path
+ 1, end
, enc
);
3389 return (char *)path
;
3392 #ifdef DOSISH_DRIVE_LETTER
3393 if (has_drive_letter(path
))
3394 return (char *)(path
+ 2);
3397 return (char *)path
;
3400 static inline char *
3401 skipprefixroot(const char *path
, const char *end
, rb_encoding
*enc
)
3403 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3404 char *p
= skipprefix(path
, end
, enc
);
3405 while (isdirsep(*p
)) p
++;
3408 return skiproot(path
, end
, enc
);
3412 #define strrdirsep rb_enc_path_last_separator
3414 rb_enc_path_last_separator(const char *path
, const char *end
, rb_encoding
*enc
)
3417 while (path
< end
) {
3418 if (isdirsep(*path
)) {
3419 const char *tmp
= path
++;
3420 while (path
< end
&& isdirsep(*path
)) path
++;
3421 if (path
>= end
) break;
3425 Inc(path
, end
, enc
);
3432 chompdirsep(const char *path
, const char *end
, rb_encoding
*enc
)
3434 while (path
< end
) {
3435 if (isdirsep(*path
)) {
3436 const char *last
= path
++;
3437 while (path
< end
&& isdirsep(*path
)) path
++;
3438 if (path
>= end
) return (char *)last
;
3441 Inc(path
, end
, enc
);
3444 return (char *)path
;
3448 rb_enc_path_end(const char *path
, const char *end
, rb_encoding
*enc
)
3450 if (path
< end
&& isdirsep(*path
)) path
++;
3451 return chompdirsep(path
, end
, enc
);
3454 static rb_encoding
*
3455 fs_enc_check(VALUE path1
, VALUE path2
)
3457 rb_encoding
*enc
= rb_enc_check(path1
, path2
);
3458 int encidx
= rb_enc_to_index(enc
);
3459 if (encidx
== ENCINDEX_US_ASCII
) {
3460 encidx
= rb_enc_get_index(path1
);
3461 if (encidx
== ENCINDEX_US_ASCII
)
3462 encidx
= rb_enc_get_index(path2
);
3463 enc
= rb_enc_from_index(encidx
);
3470 ntfs_tail(const char *path
, const char *end
, rb_encoding
*enc
)
3472 while (path
< end
&& *path
== '.') path
++;
3473 while (path
< end
&& !isADS(*path
)) {
3474 if (istrailinggarbage(*path
)) {
3475 const char *last
= path
++;
3476 while (path
< end
&& istrailinggarbage(*path
)) path
++;
3477 if (path
>= end
|| isADS(*path
)) return (char *)last
;
3479 else if (isdirsep(*path
)) {
3480 const char *last
= path
++;
3481 while (path
< end
&& isdirsep(*path
)) path
++;
3482 if (path
>= end
) return (char *)last
;
3483 if (isADS(*path
)) path
++;
3486 Inc(path
, end
, enc
);
3489 return (char *)path
;
3493 #define BUFCHECK(cond) do {\
3496 do {buflen *= 2;} while (cond);\
3497 rb_str_resize(result, buflen);\
3498 buf = RSTRING_PTR(result);\
3500 pend = buf + buflen;\
3504 #define BUFINIT() (\
3505 p = buf = RSTRING_PTR(result),\
3506 buflen = RSTRING_LEN(result),\
3510 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3512 # define SKIPPATHSEP(p) 1
3515 #define BUFCOPY(srcptr, srclen) do { \
3516 const int skip = SKIPPATHSEP(p); \
3517 rb_str_set_len(result, p-buf+skip); \
3518 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
3520 memcpy(p, (srcptr), (srclen)); \
3524 #define WITH_ROOTDIFF(stmt) do { \
3525 long rootdiff = root - buf; \
3527 root = buf + rootdiff; \
3531 copy_home_path(VALUE result
, const char *dir
)
3534 #if defined DOSISH || defined __CYGWIN__
3541 dirlen
= strlen(dir
);
3542 rb_str_resize(result
, dirlen
);
3543 memcpy(buf
= RSTRING_PTR(result
), dir
, dirlen
);
3544 encidx
= rb_filesystem_encindex();
3545 rb_enc_associate_index(result
, encidx
);
3546 #if defined DOSISH || defined __CYGWIN__
3547 enc
= rb_enc_from_index(encidx
);
3548 for (bend
= (p
= buf
) + dirlen
; p
< bend
; Inc(p
, bend
, enc
)) {
3558 rb_home_dir_of(VALUE user
, VALUE result
)
3561 struct passwd
*pwPtr
;
3563 extern char *getlogin(void);
3564 const char *pwPtr
= 0;
3565 # define endpwent() ((void)0)
3567 const char *dir
, *username
= RSTRING_PTR(user
);
3568 rb_encoding
*enc
= rb_enc_get(user
);
3570 rb_encoding
*fsenc
= rb_utf8_encoding();
3572 rb_encoding
*fsenc
= rb_filesystem_encoding();
3575 dir
= username
= RSTRING_PTR(rb_str_conv_enc(user
, enc
, fsenc
));
3579 pwPtr
= getpwnam(username
);
3581 if (strcasecmp(username
, getlogin()) == 0)
3582 dir
= pwPtr
= getenv("HOME");
3586 rb_raise(rb_eArgError
, "user %"PRIsVALUE
" doesn't exist", user
);
3589 dir
= pwPtr
->pw_dir
;
3591 copy_home_path(result
, dir
);
3598 rb_default_home_dir(VALUE result
)
3600 const char *dir
= getenv("HOME");
3602 #if defined HAVE_PWD_H
3604 /* We'll look up the user's default home dir in the password db by
3605 * login name, if possible, and failing that will fall back to looking
3606 * the information up by uid (as would be needed for processes that
3607 * are not a descendant of login(1) or a work-alike).
3609 * While the lookup by uid is more likely to succeed (since we always
3610 * have a uid, but may or may not have a login name), we prefer first
3611 * looking up by name to accommodate the possibility of multiple login
3612 * names (each with its own record in the password database, so each
3613 * with a potentially different home directory) being mapped to the
3614 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
3616 VALUE login_name
= rb_getlogin();
3618 # if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
3619 /* This is a corner case, but for backward compatibility reasons we
3620 * want to emit this error if neither the lookup by login name nor
3621 * lookup by getuid() has a chance of succeeding.
3623 if (NIL_P(login_name
)) {
3624 rb_raise(rb_eArgError
, "couldn't find login name -- expanding `~'");
3628 VALUE pw_dir
= rb_getpwdirnam_for_login(login_name
);
3629 if (NIL_P(pw_dir
)) {
3630 pw_dir
= rb_getpwdiruid();
3631 if (NIL_P(pw_dir
)) {
3632 rb_raise(rb_eArgError
, "couldn't find home for uid `%ld'", (long)getuid());
3637 copy_home_path(result
, RSTRING_PTR(pw_dir
));
3638 rb_str_resize(pw_dir
, 0);
3643 rb_raise(rb_eArgError
, "couldn't find HOME environment -- expanding `~'");
3645 return copy_home_path(result
, dir
);
3649 ospath_new(const char *ptr
, long len
, rb_encoding
*fsenc
)
3651 #if NORMALIZE_UTF8PATH
3652 VALUE path
= rb_str_normalize_ospath(ptr
, len
);
3653 rb_enc_associate(path
, fsenc
);
3656 return rb_enc_str_new(ptr
, len
, fsenc
);
3661 append_fspath(VALUE result
, VALUE fname
, char *dir
, rb_encoding
**enc
, rb_encoding
*fsenc
)
3663 char *buf
, *cwdp
= dir
;
3664 VALUE dirname
= Qnil
;
3665 size_t dirlen
= strlen(dir
), buflen
= rb_str_capacity(result
);
3667 if (NORMALIZE_UTF8PATH
|| *enc
!= fsenc
) {
3668 rb_encoding
*direnc
= fs_enc_check(fname
, dirname
= ospath_new(dir
, dirlen
, fsenc
));
3669 if (direnc
!= fsenc
) {
3670 dirname
= rb_str_conv_enc(dirname
, fsenc
, direnc
);
3671 RSTRING_GETMEM(dirname
, cwdp
, dirlen
);
3673 else if (NORMALIZE_UTF8PATH
) {
3674 RSTRING_GETMEM(dirname
, cwdp
, dirlen
);
3678 do {buflen
*= 2;} while (dirlen
> buflen
);
3679 rb_str_resize(result
, buflen
);
3680 buf
= RSTRING_PTR(result
);
3681 memcpy(buf
, cwdp
, dirlen
);
3683 if (!NIL_P(dirname
)) rb_str_resize(dirname
, 0);
3684 rb_enc_associate(result
, *enc
);
3685 return buf
+ dirlen
;
3689 rb_file_expand_path_internal(VALUE fname
, VALUE dname
, int abs_mode
, int long_name
, VALUE result
)
3691 const char *s
, *b
, *fend
;
3692 char *buf
, *p
, *pend
, *root
;
3693 size_t buflen
, bdiff
;
3694 rb_encoding
*enc
, *fsenc
= rb_filesystem_encoding();
3696 s
= StringValuePtr(fname
);
3697 fend
= s
+ RSTRING_LEN(fname
);
3698 enc
= rb_enc_get(fname
);
3701 if (s
[0] == '~' && abs_mode
== 0) { /* execute only if NOT absolute_path() */
3703 if (isdirsep(s
[1]) || s
[1] == '\0') {
3706 rb_str_set_len(result
, 0);
3708 rb_default_home_dir(result
);
3711 s
= nextdirsep(b
= s
, fend
, enc
);
3712 b
++; /* b[0] is '~' */
3714 BUFCHECK(bdiff
+ userlen
>= buflen
);
3715 memcpy(p
, b
, userlen
);
3716 ENC_CODERANGE_CLEAR(result
);
3717 rb_str_set_len(result
, userlen
);
3718 rb_enc_associate(result
, enc
);
3719 rb_home_dir_of(result
, result
);
3723 if (!rb_is_absolute_path(RSTRING_PTR(result
))) {
3725 rb_enc_raise(enc
, rb_eArgError
, "non-absolute home of %.*s%.0"PRIsVALUE
,
3726 (int)userlen
, b
, fname
);
3729 rb_raise(rb_eArgError
, "non-absolute home");
3735 #ifdef DOSISH_DRIVE_LETTER
3736 /* skip drive letter */
3737 else if (has_drive_letter(s
)) {
3738 if (isdirsep(s
[2])) {
3739 /* specified drive letter, and full path */
3740 /* skip drive letter */
3741 BUFCHECK(bdiff
+ 2 >= buflen
);
3745 rb_enc_copy(result
, fname
);
3748 /* specified drive, but not full path */
3750 if (!NIL_P(dname
) && !not_same_drive(dname
, s
[0])) {
3751 rb_file_expand_path_internal(dname
, Qnil
, abs_mode
, long_name
, result
);
3753 if (has_drive_letter(p
) && TOLOWER(p
[0]) == TOLOWER(s
[0])) {
3754 /* ok, same drive */
3759 char *e
= append_fspath(result
, fname
, getcwdofdrv(*s
), &enc
, fsenc
);
3764 rb_enc_associate(result
, enc
= fs_enc_check(result
, fname
));
3767 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
3772 else if (!rb_is_absolute_path(s
)) {
3773 if (!NIL_P(dname
)) {
3774 rb_file_expand_path_internal(dname
, Qnil
, abs_mode
, long_name
, result
);
3775 rb_enc_associate(result
, fs_enc_check(result
, fname
));
3780 char *e
= append_fspath(result
, fname
, ruby_getcwd(), &enc
, fsenc
);
3784 #if defined DOSISH || defined __CYGWIN__
3786 /* specified full path, but not drive letter nor UNC */
3787 /* we need to get the drive letter or UNC share name */
3788 p
= skipprefix(buf
, p
, enc
);
3792 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
3797 do s
++; while (isdirsep(*s
));
3800 BUFCHECK(bdiff
>= buflen
);
3801 memset(buf
, '/', len
);
3802 rb_str_set_len(result
, len
);
3803 rb_enc_associate(result
, fs_enc_check(result
, fname
));
3805 if (p
> buf
&& p
[-1] == '/')
3808 rb_str_set_len(result
, p
-buf
);
3809 BUFCHECK(bdiff
+ 1 >= buflen
);
3813 rb_str_set_len(result
, p
-buf
+1);
3814 BUFCHECK(bdiff
+ 1 >= buflen
);
3816 root
= skipprefix(buf
, p
+1, enc
);
3822 if (b
== s
++) { /* beginning of path element */
3828 if (*(s
+1) == '\0' || isdirsep(*(s
+1))) {
3829 /* We must go back to the parent */
3832 if (!(n
= strrdirsep(root
, p
, enc
))) {
3842 do ++s
; while (istrailinggarbage(*s
));
3847 #if defined DOSISH || defined __CYGWIN__
3853 /* ordinary path element, beginning don't move */
3862 while (s
< fend
&& istrailinggarbage(*s
)) s
++;
3872 #if defined DOSISH || defined __CYGWIN__
3876 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
3884 int n
= ignored_char_p(s
, fend
, enc
);
3887 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
3903 static const char prime
[] = ":$DATA";
3904 enum {prime_len
= sizeof(prime
) -1};
3908 if (s
> b
+ prime_len
&& strncasecmp(s
- prime_len
, prime
, prime_len
) == 0) {
3909 /* alias of stream */
3910 /* get rid of a bug of x64 VC++ */
3911 if (isADS(*(s
- (prime_len
+1)))) {
3912 s
-= prime_len
+ 1; /* prime */
3914 else if (memchr(b
, ':', s
- prime_len
- b
)) {
3915 s
-= prime_len
; /* alternative */
3921 rb_str_set_len(result
, p
-buf
);
3923 if (p
== skiproot(buf
, p
+ !!*p
, enc
) - 1) p
++;
3927 if ((s
= strrdirsep(b
= buf
, p
, enc
)) != 0 && !strpbrk(s
, "*?")) {
3932 WIN32_FIND_DATAW wfd
;
3935 #ifdef HAVE_CYGWIN_CONV_PATH
3936 char *w32buf
= NULL
;
3937 const int flags
= CCP_POSIX_TO_WIN_A
| CCP_RELATIVE
;
3939 char w32buf
[MAXPATHLEN
];
3943 int lnk_added
= 0, is_symlink
= 0;
3947 if (lstat_without_gvl(buf
, &st
) == 0 && S_ISLNK(st
.st_mode
)) {
3949 if (len
> 4 && STRCASECMP(p
+ len
- 4, ".lnk") != 0) {
3953 path
= *buf
? buf
: "/";
3954 #ifdef HAVE_CYGWIN_CONV_PATH
3955 bufsize
= cygwin_conv_path(flags
, path
, NULL
, 0);
3958 if (lnk_added
) bufsize
+= 4;
3959 w32buf
= ALLOCA_N(char, bufsize
);
3960 if (cygwin_conv_path(flags
, path
, w32buf
, bufsize
) == 0) {
3965 bufsize
= MAXPATHLEN
;
3966 if (cygwin_conv_to_win32_path(path
, w32buf
) == 0) {
3970 if (is_symlink
&& b
== w32buf
) {
3972 strlcat(w32buf
, p
, bufsize
);
3974 strlcat(w32buf
, ".lnk", bufsize
);
3982 rb_str_set_len(result
, p
- buf
+ strlen(p
));
3983 encidx
= ENCODING_GET(result
);
3985 if (encidx
!= ENCINDEX_UTF_8
&& rb_enc_str_coderange(result
) != ENC_CODERANGE_7BIT
) {
3986 tmp
= rb_str_encode_ospath(result
);
3988 len
= MultiByteToWideChar(CP_UTF8
, 0, RSTRING_PTR(tmp
), -1, NULL
, 0);
3989 wstr
= ALLOCV_N(WCHAR
, v
, len
);
3990 MultiByteToWideChar(CP_UTF8
, 0, RSTRING_PTR(tmp
), -1, wstr
, len
);
3991 if (tmp
!= result
) rb_str_set_len(tmp
, 0);
3992 h
= FindFirstFileW(wstr
, &wfd
);
3994 if (h
!= INVALID_HANDLE_VALUE
) {
3997 len
= lstrlenW(wfd
.cFileName
);
3999 if (lnk_added
&& len
> 4 &&
4000 wcscasecmp(wfd
.cFileName
+ len
- 4, L
".lnk") == 0) {
4001 wfd
.cFileName
[len
-= 4] = L
'\0';
4008 len
= WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, NULL
, 0, NULL
, NULL
);
4009 if (tmp
== result
) {
4010 BUFCHECK(bdiff
+ len
>= buflen
);
4011 WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, p
, len
+ 1, NULL
, NULL
);
4014 rb_str_modify_expand(tmp
, len
);
4015 WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, RSTRING_PTR(tmp
), len
+ 1, NULL
, NULL
);
4016 rb_str_cat_conv_enc_opts(result
, bdiff
, RSTRING_PTR(tmp
), len
,
4017 rb_utf8_encoding(), 0, Qnil
);
4019 rb_str_resize(tmp
, 0);
4031 rb_str_set_len(result
, p
- buf
);
4032 rb_enc_check(fname
, result
);
4033 ENC_CODERANGE_CLEAR(result
);
4038 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, MAXPATHLEN + 2)
4041 str_shrink(VALUE str
)
4043 rb_str_resize(str
, RSTRING_LEN(str
));
4047 #define expand_path(fname, dname, abs_mode, long_name, result) \
4048 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
4050 #define check_expand_path_args(fname, dname) \
4051 (((fname) = rb_get_path(fname)), \
4052 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
4055 file_expand_path_1(VALUE fname
)
4057 return rb_file_expand_path_internal(fname
, Qnil
, 0, 0, EXPAND_PATH_BUFFER());
4061 rb_file_expand_path(VALUE fname
, VALUE dname
)
4063 check_expand_path_args(fname
, dname
);
4064 return expand_path(fname
, dname
, 0, 1, EXPAND_PATH_BUFFER());
4068 rb_file_expand_path_fast(VALUE fname
, VALUE dname
)
4070 return expand_path(fname
, dname
, 0, 0, EXPAND_PATH_BUFFER());
4074 rb_file_s_expand_path(int argc
, const VALUE
*argv
)
4076 rb_check_arity(argc
, 1, 2);
4077 return rb_file_expand_path(argv
[0], argc
> 1 ? argv
[1] : Qnil
);
4082 * File.expand_path(file_name [, dir_string] ) -> abs_file_name
4084 * Converts a pathname to an absolute pathname. Relative paths are
4085 * referenced from the current working directory of the process unless
4086 * +dir_string+ is given, in which case it will be used as the
4087 * starting point. The given pathname may start with a
4088 * ``<code>~</code>'', which expands to the process owner's home
4089 * directory (the environment variable +HOME+ must be set
4090 * correctly). ``<code>~</code><i>user</i>'' expands to the named
4091 * user's home directory.
4093 * File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
4095 * A simple example of using +dir_string+ is as follows.
4096 * File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
4098 * A more complex example which also resolves parent directory is as follows.
4099 * Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
4101 * File.expand_path("../../lib/mygem.rb", __FILE__)
4102 * #=> ".../path/to/project/lib/mygem.rb"
4104 * So first it resolves the parent of __FILE__, that is bin/, then go to the
4105 * parent, the root of the project and appends +lib/mygem.rb+.
4109 s_expand_path(int c
, const VALUE
* v
, VALUE _
)
4111 return rb_file_s_expand_path(c
, v
);
4115 rb_file_absolute_path(VALUE fname
, VALUE dname
)
4117 check_expand_path_args(fname
, dname
);
4118 return expand_path(fname
, dname
, 1, 1, EXPAND_PATH_BUFFER());
4122 rb_file_s_absolute_path(int argc
, const VALUE
*argv
)
4124 rb_check_arity(argc
, 1, 2);
4125 return rb_file_absolute_path(argv
[0], argc
> 1 ? argv
[1] : Qnil
);
4130 * File.absolute_path(file_name [, dir_string] ) -> abs_file_name
4132 * Converts a pathname to an absolute pathname. Relative paths are
4133 * referenced from the current working directory of the process unless
4134 * <i>dir_string</i> is given, in which case it will be used as the
4135 * starting point. If the given pathname starts with a ``<code>~</code>''
4136 * it is NOT expanded, it is treated as a normal directory name.
4138 * File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4142 s_absolute_path(int c
, const VALUE
* v
, VALUE _
)
4144 return rb_file_s_absolute_path(c
, v
);
4149 * File.absolute_path?(file_name) -> true or false
4151 * Returns <code>true</code> if +file_name+ is an absolute path, and
4152 * <code>false</code> otherwise.
4154 * File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4158 s_absolute_path_p(VALUE klass
, VALUE fname
)
4160 VALUE path
= rb_get_path(fname
);
4162 if (!rb_is_absolute_path(RSTRING_PTR(path
))) return Qfalse
;
4166 enum rb_realpath_mode
{
4170 RB_REALPATH_MODE_MAX
4174 realpath_rec(long *prefixlenp
, VALUE
*resolvedp
, const char *unresolved
, VALUE fallback
,
4175 VALUE loopcheck
, enum rb_realpath_mode mode
, int last
)
4177 const char *pend
= unresolved
+ strlen(unresolved
);
4178 rb_encoding
*enc
= rb_enc_get(*resolvedp
);
4180 CONST_ID(resolving
, "resolving");
4181 while (unresolved
< pend
) {
4182 const char *testname
= unresolved
;
4183 const char *unresolved_firstsep
= rb_enc_path_next(unresolved
, pend
, enc
);
4184 long testnamelen
= unresolved_firstsep
- unresolved
;
4185 const char *unresolved_nextname
= unresolved_firstsep
;
4186 while (unresolved_nextname
< pend
&& isdirsep(*unresolved_nextname
))
4187 unresolved_nextname
++;
4188 unresolved
= unresolved_nextname
;
4189 if (testnamelen
== 1 && testname
[0] == '.') {
4191 else if (testnamelen
== 2 && testname
[0] == '.' && testname
[1] == '.') {
4192 if (*prefixlenp
< RSTRING_LEN(*resolvedp
)) {
4193 const char *resolved_str
= RSTRING_PTR(*resolvedp
);
4194 const char *resolved_names
= resolved_str
+ *prefixlenp
;
4195 const char *lastsep
= strrdirsep(resolved_names
, resolved_str
+ RSTRING_LEN(*resolvedp
), enc
);
4196 long len
= lastsep
? lastsep
- resolved_names
: 0;
4197 rb_str_resize(*resolvedp
, *prefixlenp
+ len
);
4202 VALUE testpath
= rb_str_dup(*resolvedp
);
4203 if (*prefixlenp
< RSTRING_LEN(testpath
))
4204 rb_str_cat2(testpath
, "/");
4205 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4206 if (*prefixlenp
> 1 && *prefixlenp
== RSTRING_LEN(testpath
)) {
4207 const char *prefix
= RSTRING_PTR(testpath
);
4208 const char *last
= rb_enc_left_char_head(prefix
, prefix
+ *prefixlenp
- 1, prefix
+ *prefixlenp
, enc
);
4209 if (!isdirsep(*last
)) rb_str_cat2(testpath
, "/");
4212 rb_str_cat(testpath
, testname
, testnamelen
);
4213 checkval
= rb_hash_aref(loopcheck
, testpath
);
4214 if (!NIL_P(checkval
)) {
4215 if (checkval
== ID2SYM(resolving
)) {
4216 if (mode
== RB_REALPATH_CHECK
) {
4220 rb_syserr_fail_path(ELOOP
, testpath
);
4223 *resolvedp
= rb_str_dup(checkval
);
4229 ret
= lstat_without_gvl(RSTRING_PTR(testpath
), &sbuf
);
4232 if (e
== ENOENT
&& !NIL_P(fallback
)) {
4233 if (stat_without_gvl(RSTRING_PTR(fallback
), &sbuf
) == 0) {
4234 rb_str_replace(*resolvedp
, fallback
);
4238 if (mode
== RB_REALPATH_CHECK
) return -1;
4240 if (mode
== RB_REALPATH_STRICT
|| !last
|| *unresolved_firstsep
)
4241 rb_syserr_fail_path(e
, testpath
);
4242 *resolvedp
= testpath
;
4246 rb_syserr_fail_path(e
, testpath
);
4249 #ifdef HAVE_READLINK
4250 if (S_ISLNK(sbuf
.st_mode
)) {
4252 VALUE link_orig
= Qnil
;
4253 const char *link_prefix
, *link_names
;
4254 long link_prefixlen
;
4255 rb_hash_aset(loopcheck
, testpath
, ID2SYM(resolving
));
4256 link
= rb_readlink(testpath
, enc
);
4257 link_prefix
= RSTRING_PTR(link
);
4258 link_names
= skipprefixroot(link_prefix
, link_prefix
+ RSTRING_LEN(link
), rb_enc_get(link
));
4259 link_prefixlen
= link_names
- link_prefix
;
4260 if (link_prefixlen
> 0) {
4261 rb_encoding
*tmpenc
, *linkenc
= rb_enc_get(link
);
4263 link
= rb_str_subseq(link
, 0, link_prefixlen
);
4264 tmpenc
= fs_enc_check(*resolvedp
, link
);
4265 if (tmpenc
!= linkenc
) link
= rb_str_conv_enc(link
, linkenc
, tmpenc
);
4267 *prefixlenp
= link_prefixlen
;
4269 if (realpath_rec(prefixlenp
, resolvedp
, link_names
, testpath
,
4270 loopcheck
, mode
, !*unresolved_firstsep
))
4272 RB_GC_GUARD(link_orig
);
4273 rb_hash_aset(loopcheck
, testpath
, rb_str_dup_frozen(*resolvedp
));
4278 VALUE s
= rb_str_dup_frozen(testpath
);
4279 rb_hash_aset(loopcheck
, s
, s
);
4280 *resolvedp
= testpath
;
4289 rb_check_realpath_emulate(VALUE basedir
, VALUE path
, rb_encoding
*origenc
, enum rb_realpath_mode mode
)
4293 VALUE unresolved_path
;
4295 VALUE curdir
= Qnil
;
4298 char *path_names
= NULL
, *basedir_names
= NULL
, *curdir_names
= NULL
;
4299 char *ptr
, *prefixptr
= NULL
, *pend
;
4302 unresolved_path
= rb_str_dup_frozen(path
);
4304 if (!NIL_P(basedir
)) {
4305 FilePathValue(basedir
);
4306 basedir
= TO_OSPATH(rb_str_dup_frozen(basedir
));
4309 enc
= rb_enc_get(unresolved_path
);
4310 unresolved_path
= TO_OSPATH(unresolved_path
);
4311 RSTRING_GETMEM(unresolved_path
, ptr
, len
);
4312 path_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(unresolved_path
));
4313 if (ptr
!= path_names
) {
4314 resolved
= rb_str_subseq(unresolved_path
, 0, path_names
- ptr
);
4318 if (!NIL_P(basedir
)) {
4319 RSTRING_GETMEM(basedir
, ptr
, len
);
4320 basedir_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(basedir
));
4321 if (ptr
!= basedir_names
) {
4322 resolved
= rb_str_subseq(basedir
, 0, basedir_names
- ptr
);
4327 curdir
= rb_dir_getwd_ospath();
4328 RSTRING_GETMEM(curdir
, ptr
, len
);
4329 curdir_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(curdir
));
4330 resolved
= rb_str_subseq(curdir
, 0, curdir_names
- ptr
);
4333 RSTRING_GETMEM(resolved
, prefixptr
, prefixlen
);
4334 pend
= prefixptr
+ prefixlen
;
4335 ptr
= chompdirsep(prefixptr
, pend
, enc
);
4337 prefixlen
= ++ptr
- prefixptr
;
4338 rb_str_set_len(resolved
, prefixlen
);
4340 #ifdef FILE_ALT_SEPARATOR
4341 while (prefixptr
< ptr
) {
4342 if (*prefixptr
== FILE_ALT_SEPARATOR
) {
4345 Inc(prefixptr
, pend
, enc
);
4349 switch (rb_enc_to_index(enc
)) {
4350 case ENCINDEX_ASCII
:
4351 case ENCINDEX_US_ASCII
:
4352 rb_enc_associate_index(resolved
, rb_filesystem_encindex());
4355 loopcheck
= rb_hash_new();
4357 if (realpath_rec(&prefixlen
, &resolved
, curdir_names
, Qnil
, loopcheck
, mode
, 0))
4360 if (basedir_names
) {
4361 if (realpath_rec(&prefixlen
, &resolved
, basedir_names
, Qnil
, loopcheck
, mode
, 0))
4364 if (realpath_rec(&prefixlen
, &resolved
, path_names
, Qnil
, loopcheck
, mode
, 1))
4367 if (origenc
&& origenc
!= rb_enc_get(resolved
)) {
4368 if (rb_enc_str_asciionly_p(resolved
)) {
4369 rb_enc_associate(resolved
, origenc
);
4372 resolved
= rb_str_conv_enc(resolved
, NULL
, origenc
);
4376 RB_GC_GUARD(unresolved_path
);
4377 RB_GC_GUARD(curdir
);
4381 static VALUE
rb_file_join(VALUE ary
);
4383 #ifndef HAVE_REALPATH
4385 rb_check_realpath_emulate_try(VALUE arg
)
4387 VALUE
*args
= (VALUE
*)arg
;
4388 return rb_check_realpath_emulate(args
[0], args
[1], (rb_encoding
*)args
[2], RB_REALPATH_CHECK
);
4392 rb_check_realpath_emulate_rescue(VALUE arg
, VALUE exc
)
4396 #endif /* HAVE_REALPATH */
4399 rb_check_realpath_internal(VALUE basedir
, VALUE path
, rb_encoding
*origenc
, enum rb_realpath_mode mode
)
4401 #ifdef HAVE_REALPATH
4402 VALUE unresolved_path
;
4403 char *resolved_ptr
= NULL
;
4406 if (mode
== RB_REALPATH_DIR
) {
4407 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4410 unresolved_path
= rb_str_dup_frozen(path
);
4411 if (*RSTRING_PTR(unresolved_path
) != '/' && !NIL_P(basedir
)) {
4412 unresolved_path
= rb_file_join(rb_assoc_new(basedir
, unresolved_path
));
4414 if (origenc
) unresolved_path
= TO_OSPATH(unresolved_path
);
4416 if ((resolved_ptr
= realpath(RSTRING_PTR(unresolved_path
), NULL
)) == NULL
) {
4417 /* glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4418 returning ENOTDIR in that case.
4419 glibc realpath(3) can also return ENOENT for paths that exist,
4421 Fallback to the emulated approach in either of those cases. */
4422 if (errno
== ENOTDIR
||
4423 (errno
== ENOENT
&& rb_file_exist_p(0, unresolved_path
))) {
4424 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4427 if (mode
== RB_REALPATH_CHECK
) {
4430 rb_sys_fail_path(unresolved_path
);
4432 resolved
= ospath_new(resolved_ptr
, strlen(resolved_ptr
), rb_filesystem_encoding());
4435 # if !defined(__LINUX__) && !defined(__APPLE__)
4436 /* As `resolved` is a String in the filesystem encoding, no
4437 * conversion is needed */
4439 if (stat_without_gvl(RSTRING_PTR(resolved
), &st
) < 0) {
4440 if (mode
== RB_REALPATH_CHECK
) {
4443 rb_sys_fail_path(unresolved_path
);
4447 if (origenc
&& origenc
!= rb_enc_get(resolved
)) {
4448 if (!rb_enc_str_asciionly_p(resolved
)) {
4449 resolved
= rb_str_conv_enc(resolved
, NULL
, origenc
);
4451 rb_enc_associate(resolved
, origenc
);
4454 if (rb_enc_str_coderange(resolved
) == ENC_CODERANGE_BROKEN
) {
4455 rb_enc_associate(resolved
, rb_filesystem_encoding());
4456 if (rb_enc_str_coderange(resolved
) == ENC_CODERANGE_BROKEN
) {
4457 rb_enc_associate(resolved
, rb_ascii8bit_encoding());
4461 RB_GC_GUARD(unresolved_path
);
4464 if (mode
== RB_REALPATH_CHECK
) {
4468 arg
[2] = (VALUE
)origenc
;
4470 return rb_rescue(rb_check_realpath_emulate_try
, (VALUE
)arg
,
4471 rb_check_realpath_emulate_rescue
, Qnil
);
4474 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4476 #endif /* HAVE_REALPATH */
4480 rb_realpath_internal(VALUE basedir
, VALUE path
, int strict
)
4482 const enum rb_realpath_mode mode
=
4483 strict
? RB_REALPATH_STRICT
: RB_REALPATH_DIR
;
4484 return rb_check_realpath_internal(basedir
, path
, rb_enc_get(path
), mode
);
4488 rb_check_realpath(VALUE basedir
, VALUE path
, rb_encoding
*enc
)
4490 return rb_check_realpath_internal(basedir
, path
, enc
, RB_REALPATH_CHECK
);
4495 * File.realpath(pathname [, dir_string]) -> real_pathname
4497 * Returns the real (absolute) pathname of _pathname_ in the actual
4498 * filesystem not containing symlinks or useless dots.
4500 * If _dir_string_ is given, it is used as a base directory
4501 * for interpreting relative pathname instead of the current directory.
4503 * All components of the pathname must exist when this method is
4507 rb_file_s_realpath(int argc
, VALUE
*argv
, VALUE klass
)
4509 VALUE basedir
= (rb_check_arity(argc
, 1, 2) > 1) ? argv
[1] : Qnil
;
4510 VALUE path
= argv
[0];
4511 FilePathValue(path
);
4512 return rb_realpath_internal(basedir
, path
, 1);
4517 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4519 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4520 * The real pathname doesn't contain symlinks or useless dots.
4522 * If _dir_string_ is given, it is used as a base directory
4523 * for interpreting relative pathname instead of the current directory.
4525 * The last component of the real pathname can be nonexistent.
4528 rb_file_s_realdirpath(int argc
, VALUE
*argv
, VALUE klass
)
4530 VALUE basedir
= (rb_check_arity(argc
, 1, 2) > 1) ? argv
[1] : Qnil
;
4531 VALUE path
= argv
[0];
4532 FilePathValue(path
);
4533 return rb_realpath_internal(basedir
, path
, 0);
4537 rmext(const char *p
, long l0
, long l1
, const char *e
, long l2
, rb_encoding
*enc
)
4541 const char *s
, *last
;
4543 if (!e
|| !l2
) return 0;
4545 c
= rb_enc_codepoint_len(e
, e
+ l2
, &len1
, enc
);
4546 if (rb_enc_ascget(e
+ len1
, e
+ l2
, &len2
, enc
) == '*' && len1
+ len2
== l2
) {
4547 if (c
== '.') return l0
;
4552 if (rb_enc_codepoint_len(s
, e
, &len1
, enc
) == c
) last
= s
;
4557 if (l1
< l2
) return l1
;
4560 if (rb_enc_left_char_head(p
, s
, p
+l1
, enc
) != s
) return 0;
4561 #if CASEFOLD_FILESYSTEM
4562 #define fncomp strncasecmp
4564 #define fncomp strncmp
4566 if (fncomp(s
, e
, l2
) == 0) {
4573 ruby_enc_find_basename(const char *name
, long *baselen
, long *alllen
, rb_encoding
*enc
)
4575 const char *p
, *q
, *e
, *end
;
4576 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4581 end
= name
+ (alllen
? (size_t)*alllen
: strlen(name
));
4582 name
= skipprefix(name
, end
, enc
);
4583 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4586 while (isdirsep(*name
))
4591 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4595 #ifdef DOSISH_DRIVE_LETTER
4596 else if (*p
== ':') {
4609 if (!(p
= strrdirsep(name
, end
, enc
))) {
4613 while (isdirsep(*p
)) p
++; /* skip last / */
4616 n
= ntfs_tail(p
, end
, enc
) - p
;
4618 n
= chompdirsep(p
, end
, enc
) - p
;
4620 for (q
= p
; q
- p
< n
&& *q
== '.'; q
++);
4621 for (e
= 0; q
- p
< n
; Inc(q
, end
, enc
)) {
4622 if (*q
== '.') e
= q
;
4637 * File.basename(file_name [, suffix] ) -> base_name
4639 * Returns the last component of the filename given in
4640 * <i>file_name</i> (after first stripping trailing separators),
4641 * which can be formed using both File::SEPARATOR and
4642 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4643 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4644 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4645 * any extension will be removed.
4647 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4648 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4649 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4653 rb_file_s_basename(int argc
, VALUE
*argv
, VALUE _
)
4655 VALUE fname
, fext
, basename
;
4656 const char *name
, *p
;
4661 if (rb_check_arity(argc
, 1, 2) == 2) {
4664 enc
= check_path_encoding(fext
);
4667 FilePathStringValue(fname
);
4668 if (NIL_P(fext
) || !(enc
= rb_enc_compatible(fname
, fext
))) {
4669 enc
= rb_enc_get(fname
);
4672 if ((n
= RSTRING_LEN(fname
)) == 0 || !*(name
= RSTRING_PTR(fname
)))
4673 return rb_str_new_shared(fname
);
4675 p
= ruby_enc_find_basename(name
, &f
, &n
, enc
);
4682 fp
= StringValueCStr(fext
);
4683 if (!(f
= rmext(p
, f
, n
, fp
, RSTRING_LEN(fext
), enc
))) {
4688 if (f
== RSTRING_LEN(fname
)) return rb_str_new_shared(fname
);
4691 basename
= rb_str_new(p
, f
);
4692 rb_enc_copy(basename
, fname
);
4696 static VALUE
rb_file_dirname_n(VALUE fname
, int n
);
4700 * File.dirname(file_name, level = 1) -> dir_name
4702 * Returns all components of the filename given in <i>file_name</i>
4703 * except the last one (after first stripping trailing separators).
4704 * The filename can be formed using both File::SEPARATOR and
4705 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4706 * not <code>nil</code>.
4708 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4710 * If +level+ is given, removes the last +level+ components, not only
4713 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4714 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4718 rb_file_s_dirname(int argc
, VALUE
*argv
, VALUE klass
)
4721 if ((argc
= rb_check_arity(argc
, 1, 2)) > 1) {
4722 n
= NUM2INT(argv
[1]);
4724 return rb_file_dirname_n(argv
[0], n
);
4728 rb_file_dirname(VALUE fname
)
4730 return rb_file_dirname_n(fname
, 1);
4734 rb_file_dirname_n(VALUE fname
, int n
)
4736 const char *name
, *root
, *p
, *end
;
4742 if (n
< 0) rb_raise(rb_eArgError
, "negative level: %d", n
);
4743 FilePathStringValue(fname
);
4744 name
= StringValueCStr(fname
);
4745 end
= name
+ RSTRING_LEN(fname
);
4746 enc
= rb_enc_get(fname
);
4747 root
= skiproot(name
, end
, enc
);
4749 if (root
> name
+ 1 && isdirsep(*name
))
4750 root
= skipprefix(name
= root
- 2, end
, enc
);
4752 if (root
> name
+ 1)
4755 if (n
> (end
- root
+ 1) / 2) {
4765 if (!(p
= strrdirsep(root
, end
, enc
))) p
= root
;
4768 seps
= ALLOCV_N(const char *, sepsv
, n
);
4769 for (i
= 0; i
< n
; ++i
) seps
[i
] = root
;
4771 for (p
= root
; p
< end
; ) {
4773 const char *tmp
= p
++;
4774 while (p
< end
&& isdirsep(*p
)) p
++;
4775 if (p
>= end
) break;
4789 return rb_usascii_str_new2(".");
4790 #ifdef DOSISH_DRIVE_LETTER
4791 if (has_drive_letter(name
) && isdirsep(*(name
+ 2))) {
4792 const char *top
= skiproot(name
+ 2, end
, enc
);
4793 dirname
= rb_str_new(name
, 3);
4794 rb_str_cat(dirname
, top
, p
- top
);
4798 dirname
= rb_str_new(name
, p
- name
);
4799 #ifdef DOSISH_DRIVE_LETTER
4800 if (has_drive_letter(name
) && root
== name
+ 2 && p
- name
== 2)
4801 rb_str_cat(dirname
, ".", 1);
4803 rb_enc_copy(dirname
, fname
);
4808 * accept a String, and return the pointer of the extension.
4809 * if len is passed, set the length of extension to it.
4810 * returned pointer is in ``name'' or NULL.
4814 * end with dot dot 1
4815 * .ext dot len of .ext
4816 * .ext:stream dot len of .ext without :stream (NT only)
4820 ruby_enc_find_extname(const char *name
, long *len
, rb_encoding
*enc
)
4822 const char *p
, *e
, *end
= name
+ (len
? *len
: (long)strlen(name
));
4824 p
= strrdirsep(name
, end
, enc
); /* get the last path component */
4828 do name
= ++p
; while (isdirsep(*p
));
4831 while (*p
&& *p
== '.') p
++;
4833 if (*p
== '.' || istrailinggarbage(*p
)) {
4835 const char *last
= p
++, *dot
= last
;
4836 while (istrailinggarbage(*p
)) {
4837 if (*p
== '.') dot
= p
;
4840 if (!*p
|| isADS(*p
)) {
4844 if (*last
== '.' || dot
> last
) e
= dot
;
4847 e
= p
; /* get the last dot of the last component */
4851 else if (isADS(*p
)) {
4855 else if (isdirsep(*p
))
4861 /* no dot, or the only dot is first or end? */
4862 if (!e
|| e
== name
)
4874 * File.extname(path) -> string
4876 * Returns the extension (the portion of file name in +path+
4877 * starting from the last period).
4879 * If +path+ is a dotfile, or starts with a period, then the starting
4880 * dot is not dealt with the start of the extension.
4882 * An empty string will also be returned when the period is the last character
4885 * On Windows, trailing dots are truncated.
4887 * File.extname("test.rb") #=> ".rb"
4888 * File.extname("a/b/d/test.rb") #=> ".rb"
4889 * File.extname(".a/b/d/test.rb") #=> ".rb"
4890 * File.extname("foo.") #=> "" on Windows
4891 * File.extname("foo.") #=> "." on non-Windows
4892 * File.extname("test") #=> ""
4893 * File.extname(".profile") #=> ""
4894 * File.extname(".profile.sh") #=> ".sh"
4899 rb_file_s_extname(VALUE klass
, VALUE fname
)
4901 const char *name
, *e
;
4905 FilePathStringValue(fname
);
4906 name
= StringValueCStr(fname
);
4907 len
= RSTRING_LEN(fname
);
4908 e
= ruby_enc_find_extname(name
, &len
, rb_enc_get(fname
));
4910 return rb_str_new(0, 0);
4911 extname
= rb_str_subseq(fname
, e
- name
, len
); /* keep the dot, too! */
4917 * File.path(path) -> string
4919 * Returns the string representation of the path
4921 * File.path("/dev/null") #=> "/dev/null"
4922 * File.path(Pathname.new("/tmp")) #=> "/tmp"
4927 rb_file_s_path(VALUE klass
, VALUE fname
)
4929 return rb_get_path(fname
);
4934 * File.split(file_name) -> array
4936 * Splits the given string into a directory and a file component and
4937 * returns them in a two-element array. See also File::dirname and
4940 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
4944 rb_file_s_split(VALUE klass
, VALUE path
)
4946 FilePathStringValue(path
); /* get rid of converting twice */
4947 return rb_assoc_new(rb_file_dirname(path
), rb_file_s_basename(1,&path
,Qundef
));
4951 file_inspect_join(VALUE ary
, VALUE arg
, int recur
)
4953 if (recur
|| ary
== arg
) rb_raise(rb_eArgError
, "recursive array");
4954 return rb_file_join(arg
);
4958 rb_file_join(VALUE ary
)
4962 const char *name
, *tail
;
4966 if (RARRAY_LEN(ary
) == 0) return rb_str_new(0, 0);
4969 for (i
=0; i
<RARRAY_LEN(ary
); i
++) {
4970 tmp
= RARRAY_AREF(ary
, i
);
4971 if (RB_TYPE_P(tmp
, T_STRING
)) {
4972 check_path_encoding(tmp
);
4973 len
+= RSTRING_LEN(tmp
);
4979 len
+= RARRAY_LEN(ary
) - 1;
4980 result
= rb_str_buf_new(len
);
4981 RBASIC_CLEAR_CLASS(result
);
4982 for (i
=0; i
<RARRAY_LEN(ary
); i
++) {
4983 tmp
= RARRAY_AREF(ary
, i
);
4984 switch (OBJ_BUILTIN_TYPE(tmp
)) {
4986 if (!checked
) check_path_encoding(tmp
);
4987 StringValueCStr(tmp
);
4991 rb_raise(rb_eArgError
, "recursive array");
4994 tmp
= rb_exec_recursive(file_inspect_join
, ary
, tmp
);
4998 FilePathStringValue(tmp
);
5001 RSTRING_GETMEM(result
, name
, len
);
5003 rb_enc_copy(result
, tmp
);
5006 tail
= chompdirsep(name
, name
+ len
, rb_enc_get(result
));
5007 if (RSTRING_PTR(tmp
) && isdirsep(RSTRING_PTR(tmp
)[0])) {
5008 rb_str_set_len(result
, tail
- name
);
5011 rb_str_cat(result
, "/", 1);
5014 enc
= fs_enc_check(result
, tmp
);
5015 rb_str_buf_append(result
, tmp
);
5016 rb_enc_associate(result
, enc
);
5018 RBASIC_SET_CLASS_RAW(result
, rb_cString
);
5025 * File.join(string, ...) -> string
5027 * Returns a new string formed by joining the strings using
5030 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5035 rb_file_s_join(VALUE klass
, VALUE args
)
5037 return rb_file_join(args
);
5040 #if defined(HAVE_TRUNCATE) || defined(HAVE_CHSIZE)
5041 struct truncate_arg
{
5043 #if defined(HAVE_TRUNCATE)
5044 #define NUM2POS(n) NUM2OFFT(n)
5047 #define NUM2POS(n) NUM2LONG(n)
5053 nogvl_truncate(void *ptr
)
5055 struct truncate_arg
*ta
= ptr
;
5056 #ifdef HAVE_TRUNCATE
5057 return (void *)(VALUE
)truncate(ta
->path
, ta
->pos
);
5058 #else /* defined(HAVE_CHSIZE) */
5060 int tmpfd
= rb_cloexec_open(ta
->path
, 0, 0);
5064 rb_update_max_fd(tmpfd
);
5065 if (chsize(tmpfd
, ta
->pos
) < 0) {
5079 * File.truncate(file_name, integer) -> 0
5081 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5082 * bytes long. Not available on all platforms.
5084 * f = File.new("out", "w")
5085 * f.write("1234567890") #=> 10
5087 * File.truncate("out", 5) #=> 0
5088 * File.size("out") #=> 5
5093 rb_file_s_truncate(VALUE klass
, VALUE path
, VALUE len
)
5095 struct truncate_arg ta
;
5098 ta
.pos
= NUM2POS(len
);
5099 FilePathValue(path
);
5100 path
= rb_str_encode_ospath(path
);
5101 ta
.path
= StringValueCStr(path
);
5103 r
= (int)(VALUE
)rb_thread_call_without_gvl(nogvl_truncate
, &ta
,
5106 rb_sys_fail_path(path
);
5111 #define rb_file_s_truncate rb_f_notimplement
5114 #if defined(HAVE_FTRUNCATE) || defined(HAVE_CHSIZE)
5115 struct ftruncate_arg
{
5117 #if defined(HAVE_FTRUNCATE)
5118 #define NUM2POS(n) NUM2OFFT(n)
5121 #define NUM2POS(n) NUM2LONG(n)
5127 nogvl_ftruncate(void *ptr
)
5129 struct ftruncate_arg
*fa
= ptr
;
5131 #ifdef HAVE_FTRUNCATE
5132 return (VALUE
)ftruncate(fa
->fd
, fa
->pos
);
5133 #else /* defined(HAVE_CHSIZE) */
5134 return (VALUE
)chsize(fa
->fd
, fa
->pos
);
5140 * file.truncate(integer) -> 0
5142 * Truncates <i>file</i> to at most <i>integer</i> bytes. The file
5143 * must be opened for writing. Not available on all platforms.
5145 * f = File.new("out", "w")
5146 * f.syswrite("1234567890") #=> 10
5147 * f.truncate(5) #=> 0
5149 * File.size("out") #=> 5
5153 rb_file_truncate(VALUE obj
, VALUE len
)
5156 struct ftruncate_arg fa
;
5158 fa
.pos
= NUM2POS(len
);
5159 GetOpenFile(obj
, fptr
);
5160 if (!(fptr
->mode
& FMODE_WRITABLE
)) {
5161 rb_raise(rb_eIOError
, "not opened for writing");
5163 rb_io_flush_raw(obj
, 0);
5165 if ((int)rb_thread_io_blocking_region(nogvl_ftruncate
, &fa
, fa
.fd
) < 0) {
5166 rb_sys_fail_path(fptr
->pathv
);
5172 #define rb_file_truncate rb_f_notimplement
5189 #include <winerror.h>
5193 rb_thread_flock(void *data
)
5196 int old_errno
= errno
;
5198 int *op
= data
, ret
= flock(op
[0], op
[1]);
5201 if (GetLastError() == ERROR_NOT_LOCKED
) {
5211 * file.flock(locking_constant) -> 0 or false
5213 * Locks or unlocks a file according to <i>locking_constant</i> (a
5214 * logical <em>or</em> of the values in the table below).
5215 * Returns <code>false</code> if File::LOCK_NB is specified and the
5216 * operation would otherwise have blocked. Not available on all
5219 * Locking constants (in class File):
5221 * LOCK_EX | Exclusive lock. Only one process may hold an
5222 * | exclusive lock for a given file at a time.
5223 * ----------+------------------------------------------------
5224 * LOCK_NB | Don't block when locking. May be combined
5225 * | with other lock options using logical or.
5226 * ----------+------------------------------------------------
5227 * LOCK_SH | Shared lock. Multiple processes may each hold a
5228 * | shared lock for a given file at the same time.
5229 * ----------+------------------------------------------------
5234 * # update a counter using write lock
5235 * # don't use "w" because it truncates the file before lock.
5236 * File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
5237 * f.flock(File::LOCK_EX)
5238 * value = f.read.to_i + 1
5240 * f.write("#{value}\n")
5245 * # read the counter using read lock
5246 * File.open("counter", "r") {|f|
5247 * f.flock(File::LOCK_SH)
5254 rb_file_flock(VALUE obj
, VALUE operation
)
5258 struct timeval time
;
5260 op
[1] = op1
= NUM2INT(operation
);
5261 GetOpenFile(obj
, fptr
);
5264 if (fptr
->mode
& FMODE_WRITABLE
) {
5265 rb_io_flush_raw(obj
, 0);
5267 while ((int)rb_thread_io_blocking_region(rb_thread_flock
, op
, fptr
->fd
) < 0) {
5272 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5275 if (op1
& LOCK_NB
) return Qfalse
;
5278 time
.tv_usec
= 100 * 1000; /* 0.1 sec */
5279 rb_thread_wait_for(time
);
5280 rb_io_check_closed(fptr
);
5284 #if defined(ERESTART)
5290 rb_syserr_fail_path(e
, fptr
->pathv
);
5297 test_check(int n
, int argc
, VALUE
*argv
)
5302 rb_check_arity(argc
, n
, n
);
5303 for (i
=1; i
<n
; i
++) {
5304 if (!RB_TYPE_P(argv
[i
], T_FILE
)) {
5305 FilePathValue(argv
[i
]);
5310 #define CHECK(n) test_check((n), argc, argv)
5314 * test(cmd, file1 [, file2] ) -> obj
5316 * Uses the character +cmd+ to perform various tests on +file1+ (first
5317 * table below) or on +file1+ and +file2+ (second table).
5319 * File tests on a single file:
5321 * Cmd Returns Meaning
5322 * "A" | Time | Last access time for file1
5323 * "b" | boolean | True if file1 is a block device
5324 * "c" | boolean | True if file1 is a character device
5325 * "C" | Time | Last change time for file1
5326 * "d" | boolean | True if file1 exists and is a directory
5327 * "e" | boolean | True if file1 exists
5328 * "f" | boolean | True if file1 exists and is a regular file
5329 * "g" | boolean | True if file1 has the \CF{setgid} bit
5330 * | | set (false under NT)
5331 * "G" | boolean | True if file1 exists and has a group
5332 * | | ownership equal to the caller's group
5333 * "k" | boolean | True if file1 exists and has the sticky bit set
5334 * "l" | boolean | True if file1 exists and is a symbolic link
5335 * "M" | Time | Last modification time for file1
5336 * "o" | boolean | True if file1 exists and is owned by
5337 * | | the caller's effective uid
5338 * "O" | boolean | True if file1 exists and is owned by
5339 * | | the caller's real uid
5340 * "p" | boolean | True if file1 exists and is a fifo
5341 * "r" | boolean | True if file1 is readable by the effective
5342 * | | uid/gid of the caller
5343 * "R" | boolean | True if file is readable by the real
5344 * | | uid/gid of the caller
5345 * "s" | int/nil | If file1 has nonzero size, return the size,
5346 * | | otherwise return nil
5347 * "S" | boolean | True if file1 exists and is a socket
5348 * "u" | boolean | True if file1 has the setuid bit set
5349 * "w" | boolean | True if file1 exists and is writable by
5350 * | | the effective uid/gid
5351 * "W" | boolean | True if file1 exists and is writable by
5352 * | | the real uid/gid
5353 * "x" | boolean | True if file1 exists and is executable by
5354 * | | the effective uid/gid
5355 * "X" | boolean | True if file1 exists and is executable by
5356 * | | the real uid/gid
5357 * "z" | boolean | True if file1 exists and has a zero length
5359 * Tests that take two files:
5361 * "-" | boolean | True if file1 and file2 are identical
5362 * "=" | boolean | True if the modification times of file1
5363 * | | and file2 are equal
5364 * "<" | boolean | True if the modification time of file1
5365 * | | is prior to that of file2
5366 * ">" | boolean | True if the modification time of file1
5367 * | | is after that of file2
5371 rb_f_test(int argc
, VALUE
*argv
, VALUE _
)
5375 if (argc
== 0) rb_check_arity(argc
, 2, 3);
5376 cmd
= NUM2CHR(argv
[0]);
5380 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd
)) {
5384 return rb_file_blockdev_p(0, argv
[1]);
5387 return rb_file_chardev_p(0, argv
[1]);
5390 return rb_file_directory_p(0, argv
[1]);
5393 return rb_file_exist_p(0, argv
[1]);
5396 return rb_file_file_p(0, argv
[1]);
5399 return rb_file_sgid_p(0, argv
[1]);
5402 return rb_file_grpowned_p(0, argv
[1]);
5405 return rb_file_sticky_p(0, argv
[1]);
5408 return rb_file_symlink_p(0, argv
[1]);
5411 return rb_file_owned_p(0, argv
[1]);
5414 return rb_file_rowned_p(0, argv
[1]);
5417 return rb_file_pipe_p(0, argv
[1]);
5420 return rb_file_readable_p(0, argv
[1]);
5423 return rb_file_readable_real_p(0, argv
[1]);
5426 return rb_file_size_p(0, argv
[1]);
5429 return rb_file_socket_p(0, argv
[1]);
5432 return rb_file_suid_p(0, argv
[1]);
5435 return rb_file_writable_p(0, argv
[1]);
5438 return rb_file_writable_real_p(0, argv
[1]);
5441 return rb_file_executable_p(0, argv
[1]);
5444 return rb_file_executable_real_p(0, argv
[1]);
5447 return rb_file_zero_p(0, argv
[1]);
5451 if (strchr("MAC", cmd
)) {
5453 VALUE fname
= argv
[1];
5456 if (rb_stat(fname
, &st
) == -1) {
5458 FilePathValue(fname
);
5459 rb_syserr_fail_path(e
, fname
);
5464 return stat_atime(&st
);
5466 return stat_mtime(&st
);
5468 return stat_ctime(&st
);
5474 return rb_file_identical_p(0, argv
[1], argv
[2]);
5477 if (strchr("=<>", cmd
)) {
5478 struct stat st1
, st2
;
5479 struct timespec t1
, t2
;
5482 if (rb_stat(argv
[1], &st1
) < 0) return Qfalse
;
5483 if (rb_stat(argv
[2], &st2
) < 0) return Qfalse
;
5485 t1
= stat_mtimespec(&st1
);
5486 t2
= stat_mtimespec(&st2
);
5490 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
== t2
.tv_nsec
) return Qtrue
;
5494 if (t1
.tv_sec
> t2
.tv_sec
) return Qtrue
;
5495 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
> t2
.tv_nsec
) return Qtrue
;
5499 if (t1
.tv_sec
< t2
.tv_sec
) return Qtrue
;
5500 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
< t2
.tv_nsec
) return Qtrue
;
5505 /* unknown command */
5507 rb_raise(rb_eArgError
, "unknown command '%s%c'", cmd
== '\'' || cmd
== '\\' ? "\\" : "", cmd
);
5510 rb_raise(rb_eArgError
, "unknown command \"\\x%02X\"", cmd
);
5512 UNREACHABLE_RETURN(Qundef
);
5517 * Document-class: File::Stat
5519 * Objects of class File::Stat encapsulate common status information
5520 * for File objects. The information is recorded at the moment the
5521 * File::Stat object is created; changes made to the file after that
5522 * point will not be reflected. File::Stat objects are returned by
5523 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5524 * methods return platform-specific values, and not all values are
5525 * meaningful on all systems. See also Kernel#test.
5529 rb_stat_s_alloc(VALUE klass
)
5531 return stat_new_0(klass
, 0);
5537 * File::Stat.new(file_name) -> stat
5539 * Create a File::Stat object for the given file name (raising an
5540 * exception if the file doesn't exist).
5544 rb_stat_init(VALUE obj
, VALUE fname
)
5546 struct stat st
, *nst
;
5548 FilePathValue(fname
);
5549 fname
= rb_str_encode_ospath(fname
);
5550 if (STAT(StringValueCStr(fname
), &st
) == -1) {
5551 rb_sys_fail_path(fname
);
5553 if (DATA_PTR(obj
)) {
5554 xfree(DATA_PTR(obj
));
5555 DATA_PTR(obj
) = NULL
;
5557 nst
= ALLOC(struct stat
);
5559 DATA_PTR(obj
) = nst
;
5566 rb_stat_init_copy(VALUE copy
, VALUE orig
)
5570 if (!OBJ_INIT_COPY(copy
, orig
)) return copy
;
5571 if (DATA_PTR(copy
)) {
5572 xfree(DATA_PTR(copy
));
5575 if (DATA_PTR(orig
)) {
5576 nst
= ALLOC(struct stat
);
5577 *nst
= *(struct stat
*)DATA_PTR(orig
);
5578 DATA_PTR(copy
) = nst
;
5586 * stat.ftype -> string
5588 * Identifies the type of <i>stat</i>. The return string is one of:
5589 * ``<code>file</code>'', ``<code>directory</code>'',
5590 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5591 * ``<code>fifo</code>'', ``<code>link</code>'',
5592 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5594 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5599 rb_stat_ftype(VALUE obj
)
5601 return rb_file_ftype(get_stat(obj
));
5606 * stat.directory? -> true or false
5608 * Returns <code>true</code> if <i>stat</i> is a directory,
5609 * <code>false</code> otherwise.
5611 * File.stat("testfile").directory? #=> false
5612 * File.stat(".").directory? #=> true
5616 rb_stat_d(VALUE obj
)
5618 if (S_ISDIR(get_stat(obj
)->st_mode
)) return Qtrue
;
5624 * stat.pipe? -> true or false
5626 * Returns <code>true</code> if the operating system supports pipes and
5627 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5631 rb_stat_p(VALUE obj
)
5634 if (S_ISFIFO(get_stat(obj
)->st_mode
)) return Qtrue
;
5642 * stat.symlink? -> true or false
5644 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5645 * <code>false</code> if it isn't or if the operating system doesn't
5646 * support this feature. As File::stat automatically follows symbolic
5647 * links, #symlink? will always be <code>false</code> for an object
5648 * returned by File::stat.
5650 * File.symlink("testfile", "alink") #=> 0
5651 * File.stat("alink").symlink? #=> false
5652 * File.lstat("alink").symlink? #=> true
5657 rb_stat_l(VALUE obj
)
5660 if (S_ISLNK(get_stat(obj
)->st_mode
)) return Qtrue
;
5667 * stat.socket? -> true or false
5669 * Returns <code>true</code> if <i>stat</i> is a socket,
5670 * <code>false</code> if it isn't or if the operating system doesn't
5671 * support this feature.
5673 * File.stat("testfile").socket? #=> false
5678 rb_stat_S(VALUE obj
)
5681 if (S_ISSOCK(get_stat(obj
)->st_mode
)) return Qtrue
;
5689 * stat.blockdev? -> true or false
5691 * Returns <code>true</code> if the file is a block device,
5692 * <code>false</code> if it isn't or if the operating system doesn't
5693 * support this feature.
5695 * File.stat("testfile").blockdev? #=> false
5696 * File.stat("/dev/hda1").blockdev? #=> true
5701 rb_stat_b(VALUE obj
)
5704 if (S_ISBLK(get_stat(obj
)->st_mode
)) return Qtrue
;
5712 * stat.chardev? -> true or false
5714 * Returns <code>true</code> if the file is a character device,
5715 * <code>false</code> if it isn't or if the operating system doesn't
5716 * support this feature.
5718 * File.stat("/dev/tty").chardev? #=> true
5723 rb_stat_c(VALUE obj
)
5725 if (S_ISCHR(get_stat(obj
)->st_mode
)) return Qtrue
;
5732 * stat.owned? -> true or false
5734 * Returns <code>true</code> if the effective user id of the process is
5735 * the same as the owner of <i>stat</i>.
5737 * File.stat("testfile").owned? #=> true
5738 * File.stat("/etc/passwd").owned? #=> false
5743 rb_stat_owned(VALUE obj
)
5745 if (get_stat(obj
)->st_uid
== geteuid()) return Qtrue
;
5750 rb_stat_rowned(VALUE obj
)
5752 if (get_stat(obj
)->st_uid
== getuid()) return Qtrue
;
5758 * stat.grpowned? -> true or false
5760 * Returns true if the effective group id of the process is the same as
5761 * the group id of <i>stat</i>. On Windows NT, returns <code>false</code>.
5763 * File.stat("testfile").grpowned? #=> true
5764 * File.stat("/etc/passwd").grpowned? #=> false
5769 rb_stat_grpowned(VALUE obj
)
5772 if (rb_group_member(get_stat(obj
)->st_gid
)) return Qtrue
;
5779 * stat.readable? -> true or false
5781 * Returns <code>true</code> if <i>stat</i> is readable by the
5782 * effective user id of this process.
5784 * File.stat("testfile").readable? #=> true
5789 rb_stat_r(VALUE obj
)
5791 struct stat
*st
= get_stat(obj
);
5794 if (geteuid() == 0) return Qtrue
;
5797 if (rb_stat_owned(obj
))
5798 return RBOOL(st
->st_mode
& S_IRUSR
);
5801 if (rb_stat_grpowned(obj
))
5802 return RBOOL(st
->st_mode
& S_IRGRP
);
5805 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
5812 * stat.readable_real? -> true or false
5814 * Returns <code>true</code> if <i>stat</i> is readable by the real
5815 * user id of this process.
5817 * File.stat("testfile").readable_real? #=> true
5822 rb_stat_R(VALUE obj
)
5824 struct stat
*st
= get_stat(obj
);
5827 if (getuid() == 0) return Qtrue
;
5830 if (rb_stat_rowned(obj
))
5831 return RBOOL(st
->st_mode
& S_IRUSR
);
5834 if (rb_group_member(get_stat(obj
)->st_gid
))
5835 return RBOOL(st
->st_mode
& S_IRGRP
);
5838 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
5845 * stat.world_readable? -> integer or nil
5847 * If <i>stat</i> is readable by others, returns an integer
5848 * representing the file permission bits of <i>stat</i>. Returns
5849 * <code>nil</code> otherwise. The meaning of the bits is platform
5850 * dependent; on Unix systems, see <code>stat(2)</code>.
5852 * m = File.stat("/etc/passwd").world_readable? #=> 420
5853 * sprintf("%o", m) #=> "644"
5857 rb_stat_wr(VALUE obj
)
5860 struct stat
*st
= get_stat(obj
);
5861 if ((st
->st_mode
& (S_IROTH
)) == S_IROTH
) {
5862 return UINT2NUM(st
->st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
5872 * stat.writable? -> true or false
5874 * Returns <code>true</code> if <i>stat</i> is writable by the
5875 * effective user id of this process.
5877 * File.stat("testfile").writable? #=> true
5882 rb_stat_w(VALUE obj
)
5884 struct stat
*st
= get_stat(obj
);
5887 if (geteuid() == 0) return Qtrue
;
5890 if (rb_stat_owned(obj
))
5891 return RBOOL(st
->st_mode
& S_IWUSR
);
5894 if (rb_stat_grpowned(obj
))
5895 return RBOOL(st
->st_mode
& S_IWGRP
);
5898 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
5905 * stat.writable_real? -> true or false
5907 * Returns <code>true</code> if <i>stat</i> is writable by the real
5908 * user id of this process.
5910 * File.stat("testfile").writable_real? #=> true
5915 rb_stat_W(VALUE obj
)
5917 struct stat
*st
= get_stat(obj
);
5920 if (getuid() == 0) return Qtrue
;
5923 if (rb_stat_rowned(obj
))
5924 return RBOOL(st
->st_mode
& S_IWUSR
);
5927 if (rb_group_member(get_stat(obj
)->st_gid
))
5928 return RBOOL(st
->st_mode
& S_IWGRP
);
5931 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
5938 * stat.world_writable? -> integer or nil
5940 * If <i>stat</i> is writable by others, returns an integer
5941 * representing the file permission bits of <i>stat</i>. Returns
5942 * <code>nil</code> otherwise. The meaning of the bits is platform
5943 * dependent; on Unix systems, see <code>stat(2)</code>.
5945 * m = File.stat("/tmp").world_writable? #=> 511
5946 * sprintf("%o", m) #=> "777"
5950 rb_stat_ww(VALUE obj
)
5953 struct stat
*st
= get_stat(obj
);
5954 if ((st
->st_mode
& (S_IWOTH
)) == S_IWOTH
) {
5955 return UINT2NUM(st
->st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
5965 * stat.executable? -> true or false
5967 * Returns <code>true</code> if <i>stat</i> is executable or if the
5968 * operating system doesn't distinguish executable files from
5969 * nonexecutable files. The tests are made using the effective owner of
5972 * File.stat("testfile").executable? #=> false
5977 rb_stat_x(VALUE obj
)
5979 struct stat
*st
= get_stat(obj
);
5982 if (geteuid() == 0) {
5983 return RBOOL(st
->st_mode
& S_IXUGO
);
5987 if (rb_stat_owned(obj
))
5988 return RBOOL(st
->st_mode
& S_IXUSR
);
5991 if (rb_stat_grpowned(obj
))
5992 return RBOOL(st
->st_mode
& S_IXGRP
);
5995 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
6002 * stat.executable_real? -> true or false
6004 * Same as <code>executable?</code>, but tests using the real owner of
6009 rb_stat_X(VALUE obj
)
6011 struct stat
*st
= get_stat(obj
);
6014 if (getuid() == 0) {
6015 return RBOOL(st
->st_mode
& S_IXUGO
);
6019 if (rb_stat_rowned(obj
))
6020 return RBOOL(st
->st_mode
& S_IXUSR
);
6023 if (rb_group_member(get_stat(obj
)->st_gid
))
6024 return RBOOL(st
->st_mode
& S_IXGRP
);
6027 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
6034 * stat.file? -> true or false
6036 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6037 * a device file, pipe, socket, etc.).
6039 * File.stat("testfile").file? #=> true
6044 rb_stat_f(VALUE obj
)
6046 if (S_ISREG(get_stat(obj
)->st_mode
)) return Qtrue
;
6052 * stat.zero? -> true or false
6054 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6055 * <code>false</code> otherwise.
6057 * File.stat("testfile").zero? #=> false
6062 rb_stat_z(VALUE obj
)
6064 if (get_stat(obj
)->st_size
== 0) return Qtrue
;
6070 * stat.size? -> Integer or nil
6072 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6073 * the file otherwise.
6075 * File.stat("testfile").size? #=> 66
6076 * File.stat("/dev/null").size? #=> nil
6081 rb_stat_s(VALUE obj
)
6083 off_t size
= get_stat(obj
)->st_size
;
6085 if (size
== 0) return Qnil
;
6086 return OFFT2NUM(size
);
6091 * stat.setuid? -> true or false
6093 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6094 * permission bit set, <code>false</code> if it doesn't or if the
6095 * operating system doesn't support this feature.
6097 * File.stat("/bin/su").setuid? #=> true
6101 rb_stat_suid(VALUE obj
)
6104 if (get_stat(obj
)->st_mode
& S_ISUID
) return Qtrue
;
6111 * stat.setgid? -> true or false
6113 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6114 * permission bit set, <code>false</code> if it doesn't or if the
6115 * operating system doesn't support this feature.
6117 * File.stat("/usr/sbin/lpc").setgid? #=> true
6122 rb_stat_sgid(VALUE obj
)
6125 if (get_stat(obj
)->st_mode
& S_ISGID
) return Qtrue
;
6132 * stat.sticky? -> true or false
6134 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6135 * <code>false</code> if it doesn't or if the operating system doesn't
6136 * support this feature.
6138 * File.stat("testfile").sticky? #=> false
6143 rb_stat_sticky(VALUE obj
)
6146 if (get_stat(obj
)->st_mode
& S_ISVTX
) return Qtrue
;
6151 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6152 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6163 nogvl_mkfifo(void *ptr
)
6165 struct mkfifo_arg
*ma
= ptr
;
6167 return (void *)(VALUE
)mkfifo(ma
->path
, ma
->mode
);
6172 * File.mkfifo(file_name, mode=0666) => 0
6174 * Creates a FIFO special file with name _file_name_. _mode_
6175 * specifies the FIFO's permissions. It is modified by the process's
6176 * umask in the usual way: the permissions of the created file are
6181 rb_file_s_mkfifo(int argc
, VALUE
*argv
, VALUE _
)
6184 struct mkfifo_arg ma
;
6187 rb_check_arity(argc
, 1, 2);
6189 ma
.mode
= NUM2MODET(argv
[1]);
6192 FilePathValue(path
);
6193 path
= rb_str_encode_ospath(path
);
6194 ma
.path
= RSTRING_PTR(path
);
6195 if (rb_thread_call_without_gvl(nogvl_mkfifo
, &ma
, RUBY_UBF_IO
, 0)) {
6196 rb_sys_fail_path(path
);
6201 #define rb_file_s_mkfifo rb_f_notimplement
6204 static VALUE rb_mFConst
;
6207 rb_file_const(const char *name
, VALUE value
)
6209 rb_define_const(rb_mFConst
, name
, value
);
6213 rb_is_absolute_path(const char *path
)
6215 #ifdef DOSISH_DRIVE_LETTER
6216 if (has_drive_letter(path
) && isdirsep(path
[2])) return 1;
6219 if (isdirsep(path
[0]) && isdirsep(path
[1])) return 1;
6222 if (path
[0] == '/') return 1;
6227 #ifndef ENABLE_PATH_CHECK
6228 # if defined DOSISH || defined __CYGWIN__
6229 # define ENABLE_PATH_CHECK 0
6231 # define ENABLE_PATH_CHECK 1
6235 #if ENABLE_PATH_CHECK
6237 path_check_0(VALUE path
)
6240 const char *p0
= StringValueCStr(path
);
6245 if (!rb_is_absolute_path(p0
)) {
6246 char *buf
= ruby_getcwd();
6249 newpath
= rb_str_new2(buf
);
6252 rb_str_cat2(newpath
, "/");
6253 rb_str_cat2(newpath
, p0
);
6255 p0
= RSTRING_PTR(path
);
6257 e0
= p0
+ RSTRING_LEN(path
);
6258 enc
= rb_enc_get(path
);
6261 # define S_IWOTH 002
6263 if (STAT(p0
, &st
) == 0 && S_ISDIR(st
.st_mode
) && (st
.st_mode
& S_IWOTH
)
6265 && !(p
&& (st
.st_mode
& S_ISVTX
))
6267 && !access(p0
, W_OK
)) {
6268 rb_enc_warn(enc
, "Insecure world writable dir %s in PATH, mode 0%"
6269 #if SIZEOF_DEV_T > SIZEOF_INT
6270 PRI_MODET_PREFIX
"o",
6279 s
= strrdirsep(p0
, e0
, enc
);
6281 if (!s
|| s
== p0
) return 1;
6290 rb_path_check(const char *path
)
6292 #if ENABLE_PATH_CHECK
6293 const char *p0
, *p
, *pend
;
6294 const char sep
= PATH_SEP_CHAR
;
6296 if (!path
) return 1;
6298 pend
= path
+ strlen(path
);
6300 p
= strchr(path
, sep
);
6304 if (!path_check_0(rb_str_new(p0
, p
- p0
))) {
6305 return 0; /* not safe */
6308 if (p0
> pend
) break;
6309 p
= strchr(p0
, sep
);
6317 ruby_is_fd_loadable(int fd
)
6324 if (fstat(fd
, &st
) < 0)
6327 if (S_ISREG(st
.st_mode
))
6330 if (S_ISFIFO(st
.st_mode
) || S_ISCHR(st
.st_mode
))
6333 if (S_ISDIR(st
.st_mode
))
6344 rb_file_load_ok(const char *path
)
6348 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6349 FIXME: Why O_NDELAY is checked?
6351 int mode
= (O_RDONLY
|
6352 #if defined O_NONBLOCK
6354 #elif defined O_NDELAY
6358 int fd
= rb_cloexec_open(path
, mode
, 0);
6359 if (fd
== -1) return 0;
6360 rb_update_max_fd(fd
);
6361 ret
= ruby_is_fd_loadable(fd
);
6368 is_explicit_relative(const char *path
)
6370 if (*path
++ != '.') return 0;
6371 if (*path
== '.') path
++;
6372 return isdirsep(*path
);
6376 copy_path_class(VALUE path
, VALUE orig
)
6378 int encidx
= rb_enc_get_index(orig
);
6379 if (encidx
== ENCINDEX_ASCII
|| encidx
== ENCINDEX_US_ASCII
)
6380 encidx
= rb_filesystem_encindex();
6381 rb_enc_associate_index(path
, encidx
);
6383 RBASIC_SET_CLASS(path
, rb_obj_class(orig
));
6389 rb_find_file_ext(VALUE
*filep
, const char *const *ext
)
6391 const char *f
= StringValueCStr(*filep
);
6392 VALUE fname
= *filep
, load_path
, tmp
;
6396 if (!ext
[0]) return 0;
6399 fname
= file_expand_path_1(fname
);
6400 f
= RSTRING_PTR(fname
);
6405 if (expanded
|| rb_is_absolute_path(f
) || is_explicit_relative(f
)) {
6406 if (!expanded
) fname
= file_expand_path_1(fname
);
6407 fnlen
= RSTRING_LEN(fname
);
6408 for (i
=0; ext
[i
]; i
++) {
6409 rb_str_cat2(fname
, ext
[i
]);
6410 if (rb_file_load_ok(RSTRING_PTR(fname
))) {
6411 *filep
= copy_path_class(fname
, *filep
);
6414 rb_str_set_len(fname
, fnlen
);
6419 RB_GC_GUARD(load_path
) = rb_get_expanded_load_path();
6420 if (!load_path
) return 0;
6422 fname
= rb_str_dup(*filep
);
6423 RBASIC_CLEAR_CLASS(fname
);
6424 fnlen
= RSTRING_LEN(fname
);
6425 tmp
= rb_str_tmp_new(MAXPATHLEN
+ 2);
6426 rb_enc_associate_index(tmp
, rb_usascii_encindex());
6427 for (j
=0; ext
[j
]; j
++) {
6428 rb_str_cat2(fname
, ext
[j
]);
6429 for (i
= 0; i
< RARRAY_LEN(load_path
); i
++) {
6430 VALUE str
= RARRAY_AREF(load_path
, i
);
6432 RB_GC_GUARD(str
) = rb_get_path(str
);
6433 if (RSTRING_LEN(str
) == 0) continue;
6434 rb_file_expand_path_internal(fname
, str
, 0, 0, tmp
);
6435 if (rb_file_load_ok(RSTRING_PTR(tmp
))) {
6436 *filep
= copy_path_class(tmp
, *filep
);
6440 rb_str_set_len(fname
, fnlen
);
6442 rb_str_resize(tmp
, 0);
6443 RB_GC_GUARD(load_path
);
6448 rb_find_file(VALUE path
)
6450 VALUE tmp
, load_path
;
6451 const char *f
= StringValueCStr(path
);
6455 tmp
= file_expand_path_1(path
);
6456 path
= copy_path_class(tmp
, path
);
6457 f
= RSTRING_PTR(path
);
6461 if (expanded
|| rb_is_absolute_path(f
) || is_explicit_relative(f
)) {
6462 if (!rb_file_load_ok(f
)) return 0;
6464 path
= copy_path_class(file_expand_path_1(path
), path
);
6468 RB_GC_GUARD(load_path
) = rb_get_expanded_load_path();
6472 tmp
= rb_str_tmp_new(MAXPATHLEN
+ 2);
6473 rb_enc_associate_index(tmp
, rb_usascii_encindex());
6474 for (i
= 0; i
< RARRAY_LEN(load_path
); i
++) {
6475 VALUE str
= RARRAY_AREF(load_path
, i
);
6476 RB_GC_GUARD(str
) = rb_get_path(str
);
6477 if (RSTRING_LEN(str
) > 0) {
6478 rb_file_expand_path_internal(path
, str
, 0, 0, tmp
);
6479 f
= RSTRING_PTR(tmp
);
6480 if (rb_file_load_ok(f
)) goto found
;
6483 rb_str_resize(tmp
, 0);
6487 return 0; /* no path, no load */
6491 return copy_path_class(tmp
, path
);
6495 define_filetest_function(const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
6497 rb_define_module_function(rb_mFileTest
, name
, func
, argc
);
6498 rb_define_singleton_method(rb_cFile
, name
, func
, argc
);
6501 const char ruby_null_device
[] =
6504 #elif defined AMIGA || defined __amigaos__
6514 * A \File object is a representation of a file in the underlying platform.
6516 * \Class \File extends module FileTest, supporting such singleton methods
6517 * as <tt>File.exist?</tt>.
6519 * == \File Permissions
6521 * A \File object has _permissions_, an octal integer representing
6522 * the permissions of an actual file in the underlying platform.
6524 * Note that file permissions are quite different from the _mode_
6525 * of a file stream (\File object).
6526 * See {IO Modes}[#class-IO-label-Modes].
6528 * In a \File object, the permissions are available thus,
6529 * where method +mode+, despite its name, returns permissions:
6531 * f = File.new('t.txt')
6532 * f.lstat.mode.to_s(8) # => "100644"
6534 * On a Unix-based operating system,
6535 * the three low-order octal digits represent the permissions
6536 * for owner (6), group (4), and world (4).
6537 * The triplet of bits in each octal digit represent, respectively,
6538 * read, write, and execute permissions.
6540 * Permissions <tt>0644</tt> thus represent read-write access for owner
6541 * and read-only access for group and world.
6542 * See man pages {open(2)}[https://www.unix.com/man-page/bsd/2/open]
6543 * and {chmod(2)}[https://www.unix.com/man-page/bsd/2/chmod].
6545 * For a directory, the meaning of the execute bit changes:
6546 * when set, the directory can be searched.
6548 * Higher-order bits in permissions may indicate the type of file
6549 * (plain, directory, pipe, socket, etc.) and various other special features.
6551 * On non-Posix operating systems, permissions may include only read-only or read-write,
6552 * in which case, the remaining permission will resemble typical values.
6553 * On Windows, for instance, the default permissions are <code>0644</code>;
6554 * The only change that can be made is to make the file
6555 * read-only, which is reported as <code>0444</code>.
6557 * For a method that actually creates a file in the underlying platform
6558 * (as opposed to merely creating a \File object),
6559 * permissions may be specified:
6561 * File.new('t.tmp', File::CREAT, 0644)
6562 * File.new('t.tmp', File::CREAT, 0444)
6564 * Permissions may also be changed:
6566 * f = File.new('t.tmp', File::CREAT, 0444)
6570 * == \File Constants
6572 * Various constants for use in \File and \IO methods
6573 * may be found in module File::Constants;
6574 * an array of their names is returned by <tt>File::Constants.constants</tt>.
6578 * First, what's elsewhere. \Class \File:
6580 * - Inherits from {class IO}[IO.html#class-IO-label-What-27s+Here],
6581 * in particular, methods for creating, reading, and writing files
6582 * - Includes {module FileTest}[FileTest.html#module-FileTest-label-What-27s+Here].
6583 * which provides dozens of additional methods.
6585 * Here, class \File provides methods that are useful for:
6587 * - {Creating}[#class-File-label-Creating]
6588 * - {Querying}[#class-File-label-Querying]
6589 * - {Settings}[#class-File-label-Settings]
6590 * - {Other}[#class-File-label-Other]
6594 * - ::new:: Opens the file at the given path; returns the file.
6595 * - ::open:: Same as ::new, but when given a block will yield the file to the block,
6596 * and close the file upon exiting the block.
6597 * - ::link:: Creates a new name for an existing file using a hard link.
6598 * - ::mkfifo:: Returns the FIFO file created at the given path.
6599 * - ::symlink:: Creates a symbolic link for the given file path.
6605 * - ::absolute_path:: Returns the absolute file path for the given path.
6606 * - ::absolute_path?:: Returns whether the given path is the absolute file path.
6607 * - ::basename:: Returns the last component of the given file path.
6608 * - ::dirname:: Returns all but the last component of the given file path.
6609 * - ::expand_path:: Returns the absolute file path for the given path,
6610 * expanding <tt>~</tt> for a home directory.
6611 * - ::extname:: Returns the file extension for the given file path.
6612 * - ::fnmatch? (aliased as ::fnmatch):: Returns whether the given file path
6613 * matches the given pattern.
6614 * - ::join:: Joins path components into a single path string.
6615 * - ::path:: Returns the string representation of the given path.
6616 * - ::readlink:: Returns the path to the file at the given symbolic link.
6617 * - ::realdirpath:: Returns the real path for the given file path,
6618 * where the last component need not exist.
6619 * - ::realpath:: Returns the real path for the given file path,
6620 * where all components must exist.
6621 * - ::split:: Returns an array of two strings: the directory name and basename
6622 * of the file at the given path.
6623 * - #path (aliased as #to_path):: Returns the string representation of the given path.
6627 * - ::atime:: Returns a \Time for the most recent access to the given file.
6628 * - ::birthtime:: Returns a \Time for the creation of the given file.
6629 * - ::ctime:: Returns a \Time for the metadata change of the given file.
6630 * - ::mtime:: Returns a \Time for the most recent data modification to
6631 * the content of the given file.
6632 * - #atime:: Returns a \Time for the most recent access to +self+.
6633 * - #birthtime:: Returns a \Time the creation for +self+.
6634 * - #ctime:: Returns a \Time for the metadata change of +self+.
6635 * - #mtime:: Returns a \Time for the most recent data modification
6636 * to the content of +self+.
6640 * - ::blockdev?:: Returns whether the file at the given path is a block device.
6641 * - ::chardev?:: Returns whether the file at the given path is a character device.
6642 * - ::directory?:: Returns whether the file at the given path is a diretory.
6643 * - ::executable?:: Returns whether the file at the given path is executable
6644 * by the effective user and group of the current process.
6645 * - ::executable_real?:: Returns whether the file at the given path is executable
6646 * by the real user and group of the current process.
6647 * - ::exist?:: Returns whether the file at the given path exists.
6648 * - ::file?:: Returns whether the file at the given path is a regular file.
6649 * - ::ftype:: Returns a string giving the type of the file at the given path.
6650 * - ::grpowned?:: Returns whether the effective group of the current process
6651 * owns the file at the given path.
6652 * - ::identical?:: Returns whether the files at two given paths are identical.
6653 * - ::lstat:: Returns the File::Stat object for the last symbolic link
6654 * in the given path.
6655 * - ::owned?:: Returns whether the effective user of the current process
6656 * owns the file at the given path.
6657 * - ::pipe?:: Returns whether the file at the given path is a pipe.
6658 * - ::readable?:: Returns whether the file at the given path is readable
6659 * by the effective user and group of the current process.
6660 * - ::readable_real?:: Returns whether the file at the given path is readable
6661 * by the real user and group of the current process.
6662 * - ::setgid?:: Returns whether the setgid bit is set for the file at the given path.
6663 * - ::setuid?:: Returns whether the setuid bit is set for the file at the given path.
6664 * - ::socket?:: Returns whether the file at the given path is a socket.
6665 * - ::stat:: Returns the File::Stat object for the file at the given path.
6666 * - ::sticky?:: Returns whether the file at the given path has its sticky bit set.
6667 * - ::symlink?:: Returns whether the file at the given path is a symbolic link.
6668 * - ::umask:: Returns the umask value for the current process.
6669 * - ::world_readable?:: Returns whether the file at the given path is readable
6671 * - ::world_writable?:: Returns whether the file at the given path is writable
6673 * - ::writable?:: Returns whether the file at the given path is writable
6674 * by the effective user and group of the current process.
6675 * - ::writable_real?:: Returns whether the file at the given path is writable
6676 * by the real user and group of the current process.
6677 * - #lstat:: Returns the File::Stat object for the last symbolic link
6678 * in the path for +self+.
6682 * - ::empty? (aliased as ::zero?):: Returns whether the file at the given path
6683 * exists and is empty.
6684 * - ::size:: Returns the size (bytes) of the file at the given path.
6685 * - ::size?:: Returns +nil+ if there is no file at the given path,
6686 * or if that file is empty; otherwise returns the file size (bytes).
6687 * - #size:: Returns the size (bytes) of +self+.
6691 * - ::chmod:: Changes permissions of the file at the given path.
6692 * - ::chown:: Change ownership of the file at the given path.
6693 * - ::lchmod:: Changes permissions of the last symbolic link in the given path.
6694 * - ::lchown:: Change ownership of the last symbolic in the given path.
6695 * - ::lutime:: For each given file path, sets the access time and modification time
6696 * of the last symbolic link in the path.
6697 * - ::rename:: Moves the file at one given path to another given path.
6698 * - ::utime:: Sets the access time and modification time of each file
6699 * at the given paths.
6700 * - #flock:: Locks or unlocks +self+.
6704 * - ::truncate:: Truncates the file at the given file path to the given size.
6705 * - ::unlink (aliased as ::delete):: Deletes the file for each given file path.
6706 * - #truncate:: Truncates +self+ to the given size.
6715 rb_mFileTest
= rb_define_module("FileTest");
6716 rb_cFile
= rb_define_class("File", rb_cIO
);
6718 define_filetest_function("directory?", rb_file_directory_p
, 1);
6719 define_filetest_function("exist?", rb_file_exist_p
, 1);
6720 define_filetest_function("readable?", rb_file_readable_p
, 1);
6721 define_filetest_function("readable_real?", rb_file_readable_real_p
, 1);
6722 define_filetest_function("world_readable?", rb_file_world_readable_p
, 1);
6723 define_filetest_function("writable?", rb_file_writable_p
, 1);
6724 define_filetest_function("writable_real?", rb_file_writable_real_p
, 1);
6725 define_filetest_function("world_writable?", rb_file_world_writable_p
, 1);
6726 define_filetest_function("executable?", rb_file_executable_p
, 1);
6727 define_filetest_function("executable_real?", rb_file_executable_real_p
, 1);
6728 define_filetest_function("file?", rb_file_file_p
, 1);
6729 define_filetest_function("zero?", rb_file_zero_p
, 1);
6730 define_filetest_function("empty?", rb_file_zero_p
, 1);
6731 define_filetest_function("size?", rb_file_size_p
, 1);
6732 define_filetest_function("size", rb_file_s_size
, 1);
6733 define_filetest_function("owned?", rb_file_owned_p
, 1);
6734 define_filetest_function("grpowned?", rb_file_grpowned_p
, 1);
6736 define_filetest_function("pipe?", rb_file_pipe_p
, 1);
6737 define_filetest_function("symlink?", rb_file_symlink_p
, 1);
6738 define_filetest_function("socket?", rb_file_socket_p
, 1);
6740 define_filetest_function("blockdev?", rb_file_blockdev_p
, 1);
6741 define_filetest_function("chardev?", rb_file_chardev_p
, 1);
6743 define_filetest_function("setuid?", rb_file_suid_p
, 1);
6744 define_filetest_function("setgid?", rb_file_sgid_p
, 1);
6745 define_filetest_function("sticky?", rb_file_sticky_p
, 1);
6747 define_filetest_function("identical?", rb_file_identical_p
, 2);
6749 rb_define_singleton_method(rb_cFile
, "stat", rb_file_s_stat
, 1);
6750 rb_define_singleton_method(rb_cFile
, "lstat", rb_file_s_lstat
, 1);
6751 rb_define_singleton_method(rb_cFile
, "ftype", rb_file_s_ftype
, 1);
6753 rb_define_singleton_method(rb_cFile
, "atime", rb_file_s_atime
, 1);
6754 rb_define_singleton_method(rb_cFile
, "mtime", rb_file_s_mtime
, 1);
6755 rb_define_singleton_method(rb_cFile
, "ctime", rb_file_s_ctime
, 1);
6756 rb_define_singleton_method(rb_cFile
, "birthtime", rb_file_s_birthtime
, 1);
6758 rb_define_singleton_method(rb_cFile
, "utime", rb_file_s_utime
, -1);
6759 rb_define_singleton_method(rb_cFile
, "chmod", rb_file_s_chmod
, -1);
6760 rb_define_singleton_method(rb_cFile
, "chown", rb_file_s_chown
, -1);
6761 rb_define_singleton_method(rb_cFile
, "lchmod", rb_file_s_lchmod
, -1);
6762 rb_define_singleton_method(rb_cFile
, "lchown", rb_file_s_lchown
, -1);
6763 rb_define_singleton_method(rb_cFile
, "lutime", rb_file_s_lutime
, -1);
6765 rb_define_singleton_method(rb_cFile
, "link", rb_file_s_link
, 2);
6766 rb_define_singleton_method(rb_cFile
, "symlink", rb_file_s_symlink
, 2);
6767 rb_define_singleton_method(rb_cFile
, "readlink", rb_file_s_readlink
, 1);
6769 rb_define_singleton_method(rb_cFile
, "unlink", rb_file_s_unlink
, -1);
6770 rb_define_singleton_method(rb_cFile
, "delete", rb_file_s_unlink
, -1);
6771 rb_define_singleton_method(rb_cFile
, "rename", rb_file_s_rename
, 2);
6772 rb_define_singleton_method(rb_cFile
, "umask", rb_file_s_umask
, -1);
6773 rb_define_singleton_method(rb_cFile
, "truncate", rb_file_s_truncate
, 2);
6774 rb_define_singleton_method(rb_cFile
, "mkfifo", rb_file_s_mkfifo
, -1);
6775 rb_define_singleton_method(rb_cFile
, "expand_path", s_expand_path
, -1);
6776 rb_define_singleton_method(rb_cFile
, "absolute_path", s_absolute_path
, -1);
6777 rb_define_singleton_method(rb_cFile
, "absolute_path?", s_absolute_path_p
, 1);
6778 rb_define_singleton_method(rb_cFile
, "realpath", rb_file_s_realpath
, -1);
6779 rb_define_singleton_method(rb_cFile
, "realdirpath", rb_file_s_realdirpath
, -1);
6780 rb_define_singleton_method(rb_cFile
, "basename", rb_file_s_basename
, -1);
6781 rb_define_singleton_method(rb_cFile
, "dirname", rb_file_s_dirname
, -1);
6782 rb_define_singleton_method(rb_cFile
, "extname", rb_file_s_extname
, 1);
6783 rb_define_singleton_method(rb_cFile
, "path", rb_file_s_path
, 1);
6785 separator
= rb_fstring_lit("/");
6786 /* separates directory parts in path */
6787 rb_define_const(rb_cFile
, "Separator", separator
);
6788 /* separates directory parts in path */
6789 rb_define_const(rb_cFile
, "SEPARATOR", separator
);
6790 rb_define_singleton_method(rb_cFile
, "split", rb_file_s_split
, 1);
6791 rb_define_singleton_method(rb_cFile
, "join", rb_file_s_join
, -2);
6794 /* platform specific alternative separator */
6795 rb_define_const(rb_cFile
, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator
)));
6797 rb_define_const(rb_cFile
, "ALT_SEPARATOR", Qnil
);
6799 /* path list separator */
6800 rb_define_const(rb_cFile
, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP
));
6802 rb_define_method(rb_cIO
, "stat", rb_io_stat
, 0); /* this is IO's method */
6803 rb_define_method(rb_cFile
, "lstat", rb_file_lstat
, 0);
6805 rb_define_method(rb_cFile
, "atime", rb_file_atime
, 0);
6806 rb_define_method(rb_cFile
, "mtime", rb_file_mtime
, 0);
6807 rb_define_method(rb_cFile
, "ctime", rb_file_ctime
, 0);
6808 rb_define_method(rb_cFile
, "birthtime", rb_file_birthtime
, 0);
6809 rb_define_method(rb_cFile
, "size", file_size
, 0);
6811 rb_define_method(rb_cFile
, "chmod", rb_file_chmod
, 1);
6812 rb_define_method(rb_cFile
, "chown", rb_file_chown
, 2);
6813 rb_define_method(rb_cFile
, "truncate", rb_file_truncate
, 1);
6815 rb_define_method(rb_cFile
, "flock", rb_file_flock
, 1);
6818 * Document-module: File::Constants
6820 * File::Constants provides file-related constants. All possible
6821 * file constants are listed in the documentation but they may not all
6822 * be present on your platform.
6824 * If the underlying platform doesn't define a constant the corresponding
6825 * Ruby constant is not defined.
6827 * Your platform documentations (e.g. man open(2)) may describe more
6828 * detailed information.
6830 rb_mFConst
= rb_define_module_under(rb_cFile
, "Constants");
6831 rb_include_module(rb_cIO
, rb_mFConst
);
6833 /* open for reading only */
6834 rb_define_const(rb_mFConst
, "RDONLY", INT2FIX(O_RDONLY
));
6835 /* open for writing only */
6836 rb_define_const(rb_mFConst
, "WRONLY", INT2FIX(O_WRONLY
));
6837 /* open for reading and writing */
6838 rb_define_const(rb_mFConst
, "RDWR", INT2FIX(O_RDWR
));
6839 /* append on each write */
6840 rb_define_const(rb_mFConst
, "APPEND", INT2FIX(O_APPEND
));
6841 /* create file if it does not exist */
6842 rb_define_const(rb_mFConst
, "CREAT", INT2FIX(O_CREAT
));
6843 /* error if CREAT and the file exists */
6844 rb_define_const(rb_mFConst
, "EXCL", INT2FIX(O_EXCL
));
6845 #if defined(O_NDELAY) || defined(O_NONBLOCK)
6847 # define O_NONBLOCK O_NDELAY
6849 /* do not block on open or for data to become available */
6850 rb_define_const(rb_mFConst
, "NONBLOCK", INT2FIX(O_NONBLOCK
));
6852 /* truncate size to 0 */
6853 rb_define_const(rb_mFConst
, "TRUNC", INT2FIX(O_TRUNC
));
6855 /* not to make opened IO the controlling terminal device */
6856 rb_define_const(rb_mFConst
, "NOCTTY", INT2FIX(O_NOCTTY
));
6861 /* disable line code conversion */
6862 rb_define_const(rb_mFConst
, "BINARY", INT2FIX(O_BINARY
));
6863 #ifndef O_SHARE_DELETE
6864 # define O_SHARE_DELETE 0
6866 /* can delete opened file */
6867 rb_define_const(rb_mFConst
, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE
));
6869 /* any write operation perform synchronously */
6870 rb_define_const(rb_mFConst
, "SYNC", INT2FIX(O_SYNC
));
6873 /* any write operation perform synchronously except some meta data */
6874 rb_define_const(rb_mFConst
, "DSYNC", INT2FIX(O_DSYNC
));
6877 /* any read operation perform synchronously. used with SYNC or DSYNC. */
6878 rb_define_const(rb_mFConst
, "RSYNC", INT2FIX(O_RSYNC
));
6881 /* do not follow symlinks */
6882 rb_define_const(rb_mFConst
, "NOFOLLOW", INT2FIX(O_NOFOLLOW
)); /* FreeBSD, Linux */
6885 /* do not change atime */
6886 rb_define_const(rb_mFConst
, "NOATIME", INT2FIX(O_NOATIME
)); /* Linux */
6889 /* Try to minimize cache effects of the I/O to and from this file. */
6890 rb_define_const(rb_mFConst
, "DIRECT", INT2FIX(O_DIRECT
));
6893 /* Create an unnamed temporary file */
6894 rb_define_const(rb_mFConst
, "TMPFILE", INT2FIX(O_TMPFILE
));
6897 /* shared lock. see File#flock */
6898 rb_define_const(rb_mFConst
, "LOCK_SH", INT2FIX(LOCK_SH
));
6899 /* exclusive lock. see File#flock */
6900 rb_define_const(rb_mFConst
, "LOCK_EX", INT2FIX(LOCK_EX
));
6901 /* unlock. see File#flock */
6902 rb_define_const(rb_mFConst
, "LOCK_UN", INT2FIX(LOCK_UN
));
6903 /* non-blocking lock. used with LOCK_SH or LOCK_EX. see File#flock */
6904 rb_define_const(rb_mFConst
, "LOCK_NB", INT2FIX(LOCK_NB
));
6906 /* Name of the null device */
6907 rb_define_const(rb_mFConst
, "NULL", rb_fstring_cstr(ruby_null_device
));
6909 rb_define_method(rb_cFile
, "path", rb_file_path
, 0);
6910 rb_define_method(rb_cFile
, "to_path", rb_file_path
, 0);
6911 rb_define_global_function("test", rb_f_test
, -1);
6913 rb_cStat
= rb_define_class_under(rb_cFile
, "Stat", rb_cObject
);
6914 rb_define_alloc_func(rb_cStat
, rb_stat_s_alloc
);
6915 rb_define_method(rb_cStat
, "initialize", rb_stat_init
, 1);
6916 rb_define_method(rb_cStat
, "initialize_copy", rb_stat_init_copy
, 1);
6918 rb_include_module(rb_cStat
, rb_mComparable
);
6920 rb_define_method(rb_cStat
, "<=>", rb_stat_cmp
, 1);
6922 rb_define_method(rb_cStat
, "dev", rb_stat_dev
, 0);
6923 rb_define_method(rb_cStat
, "dev_major", rb_stat_dev_major
, 0);
6924 rb_define_method(rb_cStat
, "dev_minor", rb_stat_dev_minor
, 0);
6925 rb_define_method(rb_cStat
, "ino", rb_stat_ino
, 0);
6926 rb_define_method(rb_cStat
, "mode", rb_stat_mode
, 0);
6927 rb_define_method(rb_cStat
, "nlink", rb_stat_nlink
, 0);
6928 rb_define_method(rb_cStat
, "uid", rb_stat_uid
, 0);
6929 rb_define_method(rb_cStat
, "gid", rb_stat_gid
, 0);
6930 rb_define_method(rb_cStat
, "rdev", rb_stat_rdev
, 0);
6931 rb_define_method(rb_cStat
, "rdev_major", rb_stat_rdev_major
, 0);
6932 rb_define_method(rb_cStat
, "rdev_minor", rb_stat_rdev_minor
, 0);
6933 rb_define_method(rb_cStat
, "size", rb_stat_size
, 0);
6934 rb_define_method(rb_cStat
, "blksize", rb_stat_blksize
, 0);
6935 rb_define_method(rb_cStat
, "blocks", rb_stat_blocks
, 0);
6936 rb_define_method(rb_cStat
, "atime", rb_stat_atime
, 0);
6937 rb_define_method(rb_cStat
, "mtime", rb_stat_mtime
, 0);
6938 rb_define_method(rb_cStat
, "ctime", rb_stat_ctime
, 0);
6939 rb_define_method(rb_cStat
, "birthtime", rb_stat_birthtime
, 0);
6941 rb_define_method(rb_cStat
, "inspect", rb_stat_inspect
, 0);
6943 rb_define_method(rb_cStat
, "ftype", rb_stat_ftype
, 0);
6945 rb_define_method(rb_cStat
, "directory?", rb_stat_d
, 0);
6946 rb_define_method(rb_cStat
, "readable?", rb_stat_r
, 0);
6947 rb_define_method(rb_cStat
, "readable_real?", rb_stat_R
, 0);
6948 rb_define_method(rb_cStat
, "world_readable?", rb_stat_wr
, 0);
6949 rb_define_method(rb_cStat
, "writable?", rb_stat_w
, 0);
6950 rb_define_method(rb_cStat
, "writable_real?", rb_stat_W
, 0);
6951 rb_define_method(rb_cStat
, "world_writable?", rb_stat_ww
, 0);
6952 rb_define_method(rb_cStat
, "executable?", rb_stat_x
, 0);
6953 rb_define_method(rb_cStat
, "executable_real?", rb_stat_X
, 0);
6954 rb_define_method(rb_cStat
, "file?", rb_stat_f
, 0);
6955 rb_define_method(rb_cStat
, "zero?", rb_stat_z
, 0);
6956 rb_define_method(rb_cStat
, "size?", rb_stat_s
, 0);
6957 rb_define_method(rb_cStat
, "owned?", rb_stat_owned
, 0);
6958 rb_define_method(rb_cStat
, "grpowned?", rb_stat_grpowned
, 0);
6960 rb_define_method(rb_cStat
, "pipe?", rb_stat_p
, 0);
6961 rb_define_method(rb_cStat
, "symlink?", rb_stat_l
, 0);
6962 rb_define_method(rb_cStat
, "socket?", rb_stat_S
, 0);
6964 rb_define_method(rb_cStat
, "blockdev?", rb_stat_b
, 0);
6965 rb_define_method(rb_cStat
, "chardev?", rb_stat_c
, 0);
6967 rb_define_method(rb_cStat
, "setuid?", rb_stat_suid
, 0);
6968 rb_define_method(rb_cStat
, "setgid?", rb_stat_sgid
, 0);
6969 rb_define_method(rb_cStat
, "sticky?", rb_stat_sticky
, 0);