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 rb_file_exists_p(VALUE obj
, VALUE fname
)
1793 const char *s
= "FileTest#exist?";
1794 if (obj
== rb_mFileTest
) {
1795 s
= "FileTest.exist?";
1797 else if (obj
== rb_cFile
||
1798 (RB_TYPE_P(obj
, T_CLASS
) &&
1799 RTEST(rb_class_inherited_p(obj
, rb_cFile
)))) {
1802 rb_warn_deprecated("%.*ss?", s
, (int)(strlen(s
)-1), s
);
1803 return rb_file_exist_p(obj
, fname
);
1808 * File.readable?(file_name) -> true or false
1810 * Returns <code>true</code> if the named file is readable by the effective
1811 * user and group id of this process. See eaccess(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 effective user/group.
1818 rb_file_readable_p(VALUE obj
, VALUE fname
)
1820 return RBOOL(rb_eaccess(fname
, R_OK
) >= 0);
1825 * File.readable_real?(file_name) -> true or false
1827 * Returns <code>true</code> if the named file is readable by the real
1828 * user and group id of this process. See access(3).
1830 * Note that some OS-level security features may cause this to return true
1831 * even though the file is not readable by the real user/group.
1835 rb_file_readable_real_p(VALUE obj
, VALUE fname
)
1837 return RBOOL(rb_access(fname
, R_OK
) >= 0);
1841 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1845 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
1850 * File.world_readable?(file_name) -> integer or nil
1852 * If <i>file_name</i> is readable by others, returns an integer
1853 * representing the file permission bits of <i>file_name</i>. Returns
1854 * <code>nil</code> otherwise. The meaning of the bits is platform
1855 * dependent; on Unix systems, see <code>stat(2)</code>.
1857 * _file_name_ can be an IO object.
1859 * File.world_readable?("/etc/passwd") #=> 420
1860 * m = File.world_readable?("/etc/passwd")
1861 * sprintf("%o", m) #=> "644"
1865 rb_file_world_readable_p(VALUE obj
, VALUE fname
)
1870 if (rb_stat(fname
, &st
) < 0) return Qnil
;
1871 if ((st
.st_mode
& (S_IROTH
)) == S_IROTH
) {
1872 return UINT2NUM(st
.st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
1880 * File.writable?(file_name) -> true or false
1882 * Returns <code>true</code> if the named file is writable by the effective
1883 * user and group id of this process. See eaccess(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 effective user/group.
1890 rb_file_writable_p(VALUE obj
, VALUE fname
)
1892 return RBOOL(rb_eaccess(fname
, W_OK
) >= 0);
1897 * File.writable_real?(file_name) -> true or false
1899 * Returns <code>true</code> if the named file is writable by the real
1900 * user and group id of this process. See access(3).
1902 * Note that some OS-level security features may cause this to return true
1903 * even though the file is not writable by the real user/group.
1907 rb_file_writable_real_p(VALUE obj
, VALUE fname
)
1909 return RBOOL(rb_access(fname
, W_OK
) >= 0);
1914 * File.world_writable?(file_name) -> integer or nil
1916 * If <i>file_name</i> is writable by others, returns an integer
1917 * representing the file permission bits of <i>file_name</i>. Returns
1918 * <code>nil</code> otherwise. The meaning of the bits is platform
1919 * dependent; on Unix systems, see <code>stat(2)</code>.
1921 * _file_name_ can be an IO object.
1923 * File.world_writable?("/tmp") #=> 511
1924 * m = File.world_writable?("/tmp")
1925 * sprintf("%o", m) #=> "777"
1929 rb_file_world_writable_p(VALUE obj
, VALUE fname
)
1934 if (rb_stat(fname
, &st
) < 0) return Qnil
;
1935 if ((st
.st_mode
& (S_IWOTH
)) == S_IWOTH
) {
1936 return UINT2NUM(st
.st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
1944 * File.executable?(file_name) -> true or false
1946 * Returns <code>true</code> if the named file is executable by the effective
1947 * user and group id of this process. See eaccess(3).
1949 * Windows does not support execute permissions separately from read
1950 * permissions. On Windows, a file is only considered executable if it ends in
1951 * .bat, .cmd, .com, or .exe.
1953 * Note that some OS-level security features may cause this to return true
1954 * even though the file is not executable by the effective user/group.
1958 rb_file_executable_p(VALUE obj
, VALUE fname
)
1960 return RBOOL(rb_eaccess(fname
, X_OK
) >= 0);
1965 * File.executable_real?(file_name) -> true or false
1967 * Returns <code>true</code> if the named file is executable by the real
1968 * user and group id of this process. See access(3).
1970 * Windows does not support execute permissions separately from read
1971 * permissions. On Windows, a file is only considered executable if it ends in
1972 * .bat, .cmd, .com, or .exe.
1974 * Note that some OS-level security features may cause this to return true
1975 * even though the file is not executable by the real user/group.
1979 rb_file_executable_real_p(VALUE obj
, VALUE fname
)
1981 return RBOOL(rb_access(fname
, X_OK
) >= 0);
1985 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1990 * File.file?(file) -> true or false
1992 * Returns +true+ if the named +file+ exists and is a regular file.
1994 * +file+ can be an IO object.
1996 * If the +file+ argument is a symbolic link, it will resolve the symbolic link
1997 * and use the file referenced by the link.
2001 rb_file_file_p(VALUE obj
, VALUE fname
)
2005 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2006 return RBOOL(S_ISREG(st
.st_mode
));
2011 * File.zero?(file_name) -> true or false
2013 * Returns <code>true</code> if the named file exists and has
2016 * _file_name_ can be an IO object.
2020 rb_file_zero_p(VALUE obj
, VALUE fname
)
2024 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2025 return RBOOL(st
.st_size
== 0);
2030 * File.size?(file_name) -> Integer or nil
2032 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
2035 * _file_name_ can be an IO object.
2039 rb_file_size_p(VALUE obj
, VALUE fname
)
2043 if (rb_stat(fname
, &st
) < 0) return Qnil
;
2044 if (st
.st_size
== 0) return Qnil
;
2045 return OFFT2NUM(st
.st_size
);
2050 * File.owned?(file_name) -> true or false
2052 * Returns <code>true</code> if the named file exists and the
2053 * effective used id of the calling process is the owner of
2056 * _file_name_ can be an IO object.
2060 rb_file_owned_p(VALUE obj
, VALUE fname
)
2064 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2065 return RBOOL(st
.st_uid
== geteuid());
2069 rb_file_rowned_p(VALUE obj
, VALUE fname
)
2073 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2074 return RBOOL(st
.st_uid
== getuid());
2079 * File.grpowned?(file_name) -> true or false
2081 * Returns <code>true</code> if the named file exists and the
2082 * effective group id of the calling process is the owner of
2083 * the file. Returns <code>false</code> on Windows.
2085 * _file_name_ can be an IO object.
2089 rb_file_grpowned_p(VALUE obj
, VALUE fname
)
2094 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2095 if (rb_group_member(st
.st_gid
)) return Qtrue
;
2100 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2102 check3rdbyte(VALUE fname
, int mode
)
2106 if (rb_stat(fname
, &st
) < 0) return Qfalse
;
2107 return RBOOL(st
.st_mode
& mode
);
2113 * File.setuid?(file_name) -> true or false
2115 * Returns <code>true</code> if the named file has the setuid bit set.
2117 * _file_name_ can be an IO object.
2121 rb_file_suid_p(VALUE obj
, VALUE fname
)
2124 return check3rdbyte(fname
, S_ISUID
);
2132 * File.setgid?(file_name) -> true or false
2134 * Returns <code>true</code> if the named file has the setgid bit set.
2136 * _file_name_ can be an IO object.
2140 rb_file_sgid_p(VALUE obj
, VALUE fname
)
2143 return check3rdbyte(fname
, S_ISGID
);
2151 * File.sticky?(file_name) -> true or false
2153 * Returns <code>true</code> if the named file has the sticky bit set.
2155 * _file_name_ can be an IO object.
2159 rb_file_sticky_p(VALUE obj
, VALUE fname
)
2162 return check3rdbyte(fname
, S_ISVTX
);
2170 * File.identical?(file_1, file_2) -> true or false
2172 * Returns <code>true</code> if the named files are identical.
2174 * _file_1_ and _file_2_ can be an IO object.
2177 * p File.identical?("a", "a") #=> true
2178 * p File.identical?("a", "./a") #=> true
2179 * File.link("a", "b")
2180 * p File.identical?("a", "b") #=> true
2181 * File.symlink("a", "c")
2182 * p File.identical?("a", "c") #=> true
2184 * p File.identical?("a", "d") #=> false
2188 rb_file_identical_p(VALUE obj
, VALUE fname1
, VALUE fname2
)
2191 struct stat st1
, st2
;
2193 if (rb_stat(fname1
, &st1
) < 0) return Qfalse
;
2194 if (rb_stat(fname2
, &st2
) < 0) return Qfalse
;
2195 if (st1
.st_dev
!= st2
.st_dev
) return Qfalse
;
2196 if (st1
.st_ino
!= st2
.st_ino
) return Qfalse
;
2199 extern VALUE
rb_w32_file_identical_p(VALUE
, VALUE
);
2200 return rb_w32_file_identical_p(fname1
, fname2
);
2206 * File.size(file_name) -> integer
2208 * Returns the size of <code>file_name</code>.
2210 * _file_name_ can be an IO object.
2214 rb_file_s_size(VALUE klass
, VALUE fname
)
2218 if (rb_stat(fname
, &st
) < 0) {
2220 FilePathValue(fname
);
2221 rb_syserr_fail_path(e
, fname
);
2223 return OFFT2NUM(st
.st_size
);
2227 rb_file_ftype(const struct stat
*st
)
2231 if (S_ISREG(st
->st_mode
)) {
2234 else if (S_ISDIR(st
->st_mode
)) {
2237 else if (S_ISCHR(st
->st_mode
)) {
2238 t
= "characterSpecial";
2241 else if (S_ISBLK(st
->st_mode
)) {
2246 else if (S_ISFIFO(st
->st_mode
)) {
2251 else if (S_ISLNK(st
->st_mode
)) {
2256 else if (S_ISSOCK(st
->st_mode
)) {
2264 return rb_usascii_str_new2(t
);
2269 * File.ftype(file_name) -> string
2271 * Identifies the type of the named file; the return string is one of
2272 * ``<code>file</code>'', ``<code>directory</code>'',
2273 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
2274 * ``<code>fifo</code>'', ``<code>link</code>'',
2275 * ``<code>socket</code>'', or ``<code>unknown</code>''.
2277 * File.ftype("testfile") #=> "file"
2278 * File.ftype("/dev/tty") #=> "characterSpecial"
2279 * File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2283 rb_file_s_ftype(VALUE klass
, VALUE fname
)
2287 FilePathValue(fname
);
2288 fname
= rb_str_encode_ospath(fname
);
2289 if (lstat_without_gvl(StringValueCStr(fname
), &st
) == -1) {
2290 rb_sys_fail_path(fname
);
2293 return rb_file_ftype(&st
);
2298 * File.atime(file_name) -> time
2300 * Returns the last access time for the named file as a Time object.
2302 * _file_name_ can be an IO object.
2304 * File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2309 rb_file_s_atime(VALUE klass
, VALUE fname
)
2313 if (rb_stat(fname
, &st
) < 0) {
2315 FilePathValue(fname
);
2316 rb_syserr_fail_path(e
, fname
);
2318 return stat_atime(&st
);
2323 * file.atime -> time
2325 * Returns the last access time (a Time object) for <i>file</i>, or
2326 * epoch if <i>file</i> has not been accessed.
2328 * File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2333 rb_file_atime(VALUE obj
)
2338 GetOpenFile(obj
, fptr
);
2339 if (fstat(fptr
->fd
, &st
) == -1) {
2340 rb_sys_fail_path(fptr
->pathv
);
2342 return stat_atime(&st
);
2347 * File.mtime(file_name) -> time
2349 * Returns the modification time for the named file as a Time object.
2351 * _file_name_ can be an IO object.
2353 * File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2358 rb_file_s_mtime(VALUE klass
, VALUE fname
)
2362 if (rb_stat(fname
, &st
) < 0) {
2364 FilePathValue(fname
);
2365 rb_syserr_fail_path(e
, fname
);
2367 return stat_mtime(&st
);
2372 * file.mtime -> time
2374 * Returns the modification time for <i>file</i>.
2376 * File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2381 rb_file_mtime(VALUE obj
)
2386 GetOpenFile(obj
, fptr
);
2387 if (fstat(fptr
->fd
, &st
) == -1) {
2388 rb_sys_fail_path(fptr
->pathv
);
2390 return stat_mtime(&st
);
2395 * File.ctime(file_name) -> time
2397 * Returns the change time for the named file (the time at which
2398 * directory information about the file was changed, not the file
2401 * _file_name_ can be an IO object.
2403 * Note that on Windows (NTFS), returns creation time (birth time).
2405 * File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2410 rb_file_s_ctime(VALUE klass
, VALUE fname
)
2414 if (rb_stat(fname
, &st
) < 0) {
2416 FilePathValue(fname
);
2417 rb_syserr_fail_path(e
, fname
);
2419 return stat_ctime(&st
);
2424 * file.ctime -> time
2426 * Returns the change time for <i>file</i> (that is, the time directory
2427 * information about the file was changed, not the file itself).
2429 * Note that on Windows (NTFS), returns creation time (birth time).
2431 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2436 rb_file_ctime(VALUE obj
)
2441 GetOpenFile(obj
, fptr
);
2442 if (fstat(fptr
->fd
, &st
) == -1) {
2443 rb_sys_fail_path(fptr
->pathv
);
2445 return stat_ctime(&st
);
2450 * File.birthtime(file_name) -> time
2452 * Returns the birth time for the named file.
2454 * _file_name_ can be an IO object.
2456 * File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2458 * If the platform doesn't have birthtime, raises NotImplementedError.
2462 #if defined(HAVE_STAT_BIRTHTIME)
2463 RUBY_FUNC_EXPORTED VALUE
2464 rb_file_s_birthtime(VALUE klass
, VALUE fname
)
2468 if (rb_statx(fname
, &st
, STATX_BTIME
) < 0) {
2470 FilePathValue(fname
);
2471 rb_syserr_fail_path(e
, fname
);
2473 return statx_birthtime(&st
, fname
);
2476 # define rb_file_s_birthtime rb_f_notimplement
2479 #if defined(HAVE_STAT_BIRTHTIME)
2482 * file.birthtime -> time
2484 * Returns the birth time for <i>file</i>.
2486 * File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
2488 * If the platform doesn't have birthtime, raises NotImplementedError.
2493 rb_file_birthtime(VALUE obj
)
2498 GetOpenFile(obj
, fptr
);
2499 if (fstatx_without_gvl(fptr
->fd
, &st
, STATX_BTIME
) == -1) {
2500 rb_sys_fail_path(fptr
->pathv
);
2502 return statx_birthtime(&st
, fptr
->pathv
);
2505 # define rb_file_birthtime rb_f_notimplement
2510 * file.size -> integer
2512 * Returns the size of <i>file</i> in bytes.
2514 * File.new("testfile").size #=> 66
2519 rb_file_size(VALUE file
)
2521 if (RB_TYPE_P(file
, T_FILE
)) {
2525 RB_IO_POINTER(file
, fptr
);
2526 if (fptr
->mode
& FMODE_WRITABLE
) {
2527 rb_io_flush_raw(file
, 0);
2530 if (fstat(fptr
->fd
, &st
) == -1) {
2531 rb_sys_fail_path(fptr
->pathv
);
2537 return NUM2OFFT(rb_funcall(file
, idSize
, 0));
2542 file_size(VALUE self
)
2544 return OFFT2NUM(rb_file_size(self
));
2548 chmod_internal(const char *path
, void *mode
)
2550 return chmod(path
, *(mode_t
*)mode
);
2555 * File.chmod(mode_int, file_name, ... ) -> integer
2557 * Changes permission bits on the named file(s) to the bit pattern
2558 * represented by <i>mode_int</i>. Actual effects are operating system
2559 * dependent (see the beginning of this section). On Unix systems, see
2560 * <code>chmod(2)</code> for details. Returns the number of files
2563 * File.chmod(0644, "testfile", "out") #=> 2
2567 rb_file_s_chmod(int argc
, VALUE
*argv
, VALUE _
)
2572 mode
= NUM2MODET(*argv
++);
2574 return apply2files(chmod_internal
, argc
, argv
, &mode
);
2579 * file.chmod(mode_int) -> 0
2581 * Changes permission bits on <i>file</i> to the bit pattern
2582 * represented by <i>mode_int</i>. Actual effects are platform
2583 * dependent; on Unix systems, see <code>chmod(2)</code> for details.
2584 * Follows symbolic links. Also see File#lchmod.
2586 * f = File.new("out", "w");
2587 * f.chmod(0644) #=> 0
2591 rb_file_chmod(VALUE obj
, VALUE vmode
)
2595 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2599 mode
= NUM2MODET(vmode
);
2601 GetOpenFile(obj
, fptr
);
2603 if (fchmod(fptr
->fd
, mode
) == -1) {
2604 if (HAVE_FCHMOD
|| errno
!= ENOSYS
)
2605 rb_sys_fail_path(fptr
->pathv
);
2608 if (!HAVE_FCHMOD
) return INT2FIX(0);
2611 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2612 if (NIL_P(fptr
->pathv
)) return Qnil
;
2613 path
= rb_str_encode_ospath(fptr
->pathv
);
2614 if (chmod(RSTRING_PTR(path
), mode
) == -1)
2615 rb_sys_fail_path(fptr
->pathv
);
2621 #if defined(HAVE_LCHMOD)
2623 lchmod_internal(const char *path
, void *mode
)
2625 return lchmod(path
, *(mode_t
*)mode
);
2630 * File.lchmod(mode_int, file_name, ...) -> integer
2632 * Equivalent to File::chmod, but does not follow symbolic links (so
2633 * it will change the permissions associated with the link, not the
2634 * file referenced by the link). Often not available.
2639 rb_file_s_lchmod(int argc
, VALUE
*argv
, VALUE _
)
2644 mode
= NUM2MODET(*argv
++);
2646 return apply2files(lchmod_internal
, argc
, argv
, &mode
);
2649 #define rb_file_s_lchmod rb_f_notimplement
2652 static inline rb_uid_t
2656 return (rb_uid_t
)-1;
2661 static inline rb_gid_t
2665 return (rb_gid_t
)-1;
2676 chown_internal(const char *path
, void *arg
)
2678 struct chown_args
*args
= arg
;
2679 return chown(path
, args
->owner
, args
->group
);
2684 * File.chown(owner_int, group_int, file_name, ...) -> integer
2686 * Changes the owner and group of the named file(s) to the given
2687 * numeric owner and group id's. Only a process with superuser
2688 * privileges may change the owner of a file. The current owner of a
2689 * file may change the file's group to any group to which the owner
2690 * belongs. A <code>nil</code> or -1 owner or group id is ignored.
2691 * Returns the number of files processed.
2693 * File.chown(nil, 100, "testfile")
2698 rb_file_s_chown(int argc
, VALUE
*argv
, VALUE _
)
2700 struct chown_args arg
;
2703 arg
.owner
= to_uid(*argv
++);
2704 arg
.group
= to_gid(*argv
++);
2706 return apply2files(chown_internal
, argc
, argv
, &arg
);
2711 * file.chown(owner_int, group_int ) -> 0
2713 * Changes the owner and group of <i>file</i> to the given numeric
2714 * owner and group id's. Only a process with superuser privileges may
2715 * change the owner of a file. The current owner of a file may change
2716 * the file's group to any group to which the owner belongs. A
2717 * <code>nil</code> or -1 owner or group id is ignored. Follows
2718 * symbolic links. See also File#lchown.
2720 * File.new("testfile").chown(502, 1000)
2725 rb_file_chown(VALUE obj
, VALUE owner
, VALUE group
)
2736 GetOpenFile(obj
, fptr
);
2738 if (NIL_P(fptr
->pathv
)) return Qnil
;
2739 path
= rb_str_encode_ospath(fptr
->pathv
);
2740 if (chown(RSTRING_PTR(path
), o
, g
) == -1)
2741 rb_sys_fail_path(fptr
->pathv
);
2743 if (fchown(fptr
->fd
, o
, g
) == -1)
2744 rb_sys_fail_path(fptr
->pathv
);
2750 #if defined(HAVE_LCHOWN)
2752 lchown_internal(const char *path
, void *arg
)
2754 struct chown_args
*args
= arg
;
2755 return lchown(path
, args
->owner
, args
->group
);
2760 * File.lchown(owner_int, group_int, file_name,..) -> integer
2762 * Equivalent to File::chown, but does not follow symbolic
2763 * links (so it will change the owner associated with the link, not the
2764 * file referenced by the link). Often not available. Returns number
2765 * of files in the argument list.
2770 rb_file_s_lchown(int argc
, VALUE
*argv
, VALUE _
)
2772 struct chown_args arg
;
2775 arg
.owner
= to_uid(*argv
++);
2776 arg
.group
= to_gid(*argv
++);
2778 return apply2files(lchown_internal
, argc
, argv
, &arg
);
2781 #define rb_file_s_lchown rb_f_notimplement
2785 const struct timespec
* tsp
;
2787 int follow
; /* Whether to act on symlinks (1) or their referent (0) */
2791 NORETURN(static void utime_failed(struct apply_arg
*));
2794 utime_failed(struct apply_arg
*aa
)
2797 VALUE path
= aa
->fn
[aa
->i
].path
;
2798 struct utime_args
*ua
= aa
->arg
;
2800 if (ua
->tsp
&& e
== EINVAL
) {
2801 VALUE e
[2], a
= Qnil
, m
= Qnil
;
2803 VALUE atime
= ua
->atime
;
2804 VALUE mtime
= ua
->mtime
;
2806 if (!NIL_P(atime
)) {
2807 a
= rb_inspect(atime
);
2809 if (!NIL_P(mtime
) && mtime
!= atime
&& !rb_equal(atime
, mtime
)) {
2810 m
= rb_inspect(mtime
);
2812 if (NIL_P(a
)) e
[0] = m
;
2813 else if (NIL_P(m
) || rb_str_cmp(a
, m
) == 0) e
[0] = a
;
2815 e
[0] = rb_str_plus(a
, rb_str_new_cstr(" or "));
2816 rb_str_append(e
[0], m
);
2821 if (!d
) e
[0] = rb_str_dup(e
[0]);
2822 rb_str_append(rb_str_cat2(e
[0], " for "), path
);
2824 e
[1] = INT2FIX(EINVAL
);
2825 rb_exc_raise(rb_class_new_instance(2, e
, rb_eSystemCallError
));
2828 rb_syserr_fail_path(e
, path
);
2832 #if defined(HAVE_UTIMES)
2835 utime_internal(const char *path
, void *arg
)
2837 struct utime_args
*v
= arg
;
2838 const struct timespec
*tsp
= v
->tsp
;
2839 struct timeval tvbuf
[2], *tvp
= NULL
;
2841 #if defined(HAVE_UTIMENSAT)
2842 static int try_utimensat
= 1;
2843 # ifdef AT_SYMLINK_NOFOLLOW
2844 static int try_utimensat_follow
= 1;
2846 const int try_utimensat_follow
= 0;
2850 if (v
->follow
? try_utimensat_follow
: try_utimensat
) {
2851 # ifdef AT_SYMLINK_NOFOLLOW
2853 flags
= AT_SYMLINK_NOFOLLOW
;
2857 if (utimensat(AT_FDCWD
, path
, tsp
, flags
) < 0) {
2858 if (errno
== ENOSYS
) {
2859 # ifdef AT_SYMLINK_NOFOLLOW
2860 try_utimensat_follow
= 0;
2866 return -1; /* calls utime_failed */
2874 tvbuf
[0].tv_sec
= tsp
[0].tv_sec
;
2875 tvbuf
[0].tv_usec
= (int)(tsp
[0].tv_nsec
/ 1000);
2876 tvbuf
[1].tv_sec
= tsp
[1].tv_sec
;
2877 tvbuf
[1].tv_usec
= (int)(tsp
[1].tv_nsec
/ 1000);
2881 if (v
->follow
) return lutimes(path
, tvp
);
2883 return utimes(path
, tvp
);
2888 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
2896 utime_internal(const char *path
, void *arg
)
2898 struct utime_args
*v
= arg
;
2899 const struct timespec
*tsp
= v
->tsp
;
2900 struct utimbuf utbuf
, *utp
= NULL
;
2902 utbuf
.actime
= tsp
[0].tv_sec
;
2903 utbuf
.modtime
= tsp
[1].tv_sec
;
2906 return utime(path
, utp
);
2912 utime_internal_i(int argc
, VALUE
*argv
, int follow
)
2914 struct utime_args args
;
2915 struct timespec tss
[2], *tsp
= NULL
;
2918 args
.atime
= *argv
++;
2919 args
.mtime
= *argv
++;
2921 args
.follow
= follow
;
2923 if (!NIL_P(args
.atime
) || !NIL_P(args
.mtime
)) {
2925 tsp
[0] = rb_time_timespec(args
.atime
);
2926 if (args
.atime
== args
.mtime
)
2929 tsp
[1] = rb_time_timespec(args
.mtime
);
2933 return apply2files(utime_internal
, argc
, argv
, &args
);
2938 * File.utime(atime, mtime, file_name, ...) -> integer
2940 * Sets the access and modification times of each named file to the
2941 * first two arguments. If a file is a symlink, this method acts upon
2942 * its referent rather than the link itself; for the inverse
2943 * behavior see File.lutime. Returns the number of file
2944 * names in the argument list.
2948 rb_file_s_utime(int argc
, VALUE
*argv
, VALUE _
)
2950 return utime_internal_i(argc
, argv
, FALSE
);
2953 #if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
2957 * File.lutime(atime, mtime, file_name, ...) -> integer
2959 * Sets the access and modification times of each named file to the
2960 * first two arguments. If a file is a symlink, this method acts upon
2961 * the link itself as opposed to its referent; for the inverse
2962 * behavior, see File.utime. Returns the number of file
2963 * names in the argument list.
2967 rb_file_s_lutime(int argc
, VALUE
*argv
, VALUE _
)
2969 return utime_internal_i(argc
, argv
, TRUE
);
2972 #define rb_file_s_lutime rb_f_notimplement
2975 #ifdef RUBY_FUNCTION_NAME_STRING
2976 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
2978 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
2980 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
2981 NORETURN(static void syserr_fail2_in(const char *,int,VALUE
,VALUE
));
2983 syserr_fail2_in(const char *func
, int e
, VALUE s1
, VALUE s2
)
2987 const int max_pathlen
= MAX_PATH
;
2989 const int max_pathlen
= MAXPATHLEN
;
2993 rb_syserr_fail_path(e
, rb_str_ellipsize(s2
, max_pathlen
));
2995 str
= rb_str_new_cstr("(");
2996 rb_str_append(str
, rb_str_ellipsize(s1
, max_pathlen
));
2997 rb_str_cat2(str
, ", ");
2998 rb_str_append(str
, rb_str_ellipsize(s2
, max_pathlen
));
2999 rb_str_cat2(str
, ")");
3000 #ifdef RUBY_FUNCTION_NAME_STRING
3001 rb_syserr_fail_path_in(func
, e
, str
);
3003 rb_syserr_fail_path(e
, str
);
3010 * File.link(old_name, new_name) -> 0
3012 * Creates a new name for an existing file using a hard link. Will not
3013 * overwrite <i>new_name</i> if it already exists (raising a subclass
3014 * of SystemCallError). Not available on all platforms.
3016 * File.link("testfile", ".testfile") #=> 0
3017 * IO.readlines(".testfile")[0] #=> "This is line one\n"
3021 rb_file_s_link(VALUE klass
, VALUE from
, VALUE to
)
3023 FilePathValue(from
);
3025 from
= rb_str_encode_ospath(from
);
3026 to
= rb_str_encode_ospath(to
);
3028 if (link(StringValueCStr(from
), StringValueCStr(to
)) < 0) {
3029 sys_fail2(from
, to
);
3034 #define rb_file_s_link rb_f_notimplement
3040 * File.symlink(old_name, new_name) -> 0
3042 * Creates a symbolic link called <i>new_name</i> for the existing file
3043 * <i>old_name</i>. Raises a NotImplemented exception on
3044 * platforms that do not support symbolic links.
3046 * File.symlink("testfile", "link2test") #=> 0
3051 rb_file_s_symlink(VALUE klass
, VALUE from
, VALUE to
)
3053 FilePathValue(from
);
3055 from
= rb_str_encode_ospath(from
);
3056 to
= rb_str_encode_ospath(to
);
3058 if (symlink(StringValueCStr(from
), StringValueCStr(to
)) < 0) {
3059 sys_fail2(from
, to
);
3064 #define rb_file_s_symlink rb_f_notimplement
3067 #ifdef HAVE_READLINK
3070 * File.readlink(link_name) -> file_name
3072 * Returns the name of the file referenced by the given link.
3073 * Not available on all platforms.
3075 * File.symlink("testfile", "link2test") #=> 0
3076 * File.readlink("link2test") #=> "testfile"
3080 rb_file_s_readlink(VALUE klass
, VALUE path
)
3082 return rb_readlink(path
, rb_filesystem_encoding());
3086 struct readlink_arg
{
3093 nogvl_readlink(void *ptr
)
3095 struct readlink_arg
*ra
= ptr
;
3097 return (void *)(VALUE
)readlink(ra
->path
, ra
->buf
, ra
->size
);
3101 readlink_without_gvl(VALUE path
, VALUE buf
, size_t size
)
3103 struct readlink_arg ra
;
3105 ra
.path
= RSTRING_PTR(path
);
3106 ra
.buf
= RSTRING_PTR(buf
);
3109 return (ssize_t
)rb_thread_call_without_gvl(nogvl_readlink
, &ra
,
3114 rb_readlink(VALUE path
, rb_encoding
*enc
)
3120 FilePathValue(path
);
3121 path
= rb_str_encode_ospath(path
);
3122 v
= rb_enc_str_new(0, size
, enc
);
3123 while ((rv
= readlink_without_gvl(path
, v
, size
)) == size
3125 || (rv
< 0 && errno
== ERANGE
) /* quirky behavior of GPFS */
3128 rb_str_modify_expand(v
, size
);
3130 rb_str_set_len(v
, size
);
3134 rb_str_resize(v
, 0);
3135 rb_syserr_fail_path(e
, path
);
3137 rb_str_resize(v
, rv
);
3143 #define rb_file_s_readlink rb_f_notimplement
3147 unlink_internal(const char *path
, void *arg
)
3149 return unlink(path
);
3154 * File.delete(file_name, ...) -> integer
3155 * File.unlink(file_name, ...) -> integer
3157 * Deletes the named files, returning the number of names
3158 * passed as arguments. Raises an exception on any error.
3159 * Since the underlying implementation relies on the
3160 * <code>unlink(2)</code> system call, the type of
3161 * exception raised depends on its error type (see
3162 * https://linux.die.net/man/2/unlink) and has the form of
3163 * e.g. Errno::ENOENT.
3165 * See also Dir::rmdir.
3169 rb_file_s_unlink(int argc
, VALUE
*argv
, VALUE klass
)
3171 return apply2files(unlink_internal
, argc
, argv
, 0);
3174 struct rename_args
{
3180 no_gvl_rename(void *ptr
)
3182 struct rename_args
*ra
= ptr
;
3184 return (void *)(VALUE
)rename(ra
->src
, ra
->dst
);
3189 * File.rename(old_name, new_name) -> 0
3191 * Renames the given file to the new name. Raises a SystemCallError
3192 * if the file cannot be renamed.
3194 * File.rename("afile", "afile.bak") #=> 0
3198 rb_file_s_rename(VALUE klass
, VALUE from
, VALUE to
)
3200 struct rename_args ra
;
3203 FilePathValue(from
);
3205 f
= rb_str_encode_ospath(from
);
3206 t
= rb_str_encode_ospath(to
);
3207 ra
.src
= StringValueCStr(f
);
3208 ra
.dst
= StringValueCStr(t
);
3209 #if defined __CYGWIN__
3212 if ((int)(VALUE
)rb_thread_call_without_gvl(no_gvl_rename
, &ra
,
3213 RUBY_UBF_IO
, 0) < 0) {
3218 if (chmod(ra
.dst
, 0666) == 0 &&
3219 unlink(ra
.dst
) == 0 &&
3220 rename(ra
.src
, ra
.dst
) == 0)
3224 syserr_fail2(e
, from
, to
);
3232 * File.umask() -> integer
3233 * File.umask(integer) -> integer
3235 * Returns the current umask value for this process. If the optional
3236 * argument is given, set the umask to that value and return the
3237 * previous value. Umask values are <em>subtracted</em> from the
3238 * default permissions, so a umask of <code>0222</code> would make a
3239 * file read-only for everyone.
3241 * File.umask(0006) #=> 18
3246 rb_file_s_umask(int argc
, VALUE
*argv
, VALUE _
)
3256 omask
= umask(NUM2MODET(argv
[0]));
3259 rb_error_arity(argc
, 0, 1);
3261 return MODET2NUM(omask
);
3267 #if defined __CYGWIN__ || defined DOSISH
3269 #define DOSISH_DRIVE_LETTER
3270 #define FILE_ALT_SEPARATOR '\\'
3272 #ifdef FILE_ALT_SEPARATOR
3273 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3275 static const char file_alt_separator
[] = {FILE_ALT_SEPARATOR
, '\0'};
3278 #define isdirsep(x) ((x) == '/')
3288 #ifndef USE_NTFS_ADS
3290 # define USE_NTFS_ADS 1
3292 # define USE_NTFS_ADS 0
3297 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3299 #define istrailinggarbage(x) 0
3302 # define isADS(x) ((x) == ':')
3307 #define Next(p, e, enc) ((p) + rb_enc_mbclen((p), (e), (enc)))
3308 #define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
3310 #if defined(DOSISH_UNC)
3311 #define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
3313 #define has_unc(buf) 0
3316 #ifdef DOSISH_DRIVE_LETTER
3318 has_drive_letter(const char *buf
)
3320 if (ISALPHA(buf
[0]) && buf
[1] == ':') {
3330 getcwdofdrv(int drv
)
3333 char *drvcwd
, *oldcwd
;
3339 /* the only way that I know to get the current directory
3340 of a particular drive is to change chdir() to that drive,
3341 so save the old cwd before chdir()
3343 oldcwd
= ruby_getcwd();
3344 if (chdir(drive
) == 0) {
3345 drvcwd
= ruby_getcwd();
3350 /* perhaps the drive is not exist. we return only drive letter */
3351 drvcwd
= strdup(drive
);
3357 not_same_drive(VALUE path
, int drive
)
3359 const char *p
= RSTRING_PTR(path
);
3360 if (RSTRING_LEN(path
) < 2) return 0;
3361 if (has_drive_letter(p
)) {
3362 return TOLOWER(p
[0]) != TOLOWER(drive
);
3371 static inline char *
3372 skiproot(const char *path
, const char *end
, rb_encoding
*enc
)
3374 #ifdef DOSISH_DRIVE_LETTER
3375 if (path
+ 2 <= end
&& has_drive_letter(path
)) path
+= 2;
3377 while (path
< end
&& isdirsep(*path
)) path
++;
3378 return (char *)path
;
3381 #define nextdirsep rb_enc_path_next
3383 rb_enc_path_next(const char *s
, const char *e
, rb_encoding
*enc
)
3385 while (s
< e
&& !isdirsep(*s
)) {
3391 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3392 #define skipprefix rb_enc_path_skip_prefix
3394 #define skipprefix(path, end, enc) (path)
3397 rb_enc_path_skip_prefix(const char *path
, const char *end
, rb_encoding
*enc
)
3399 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3401 if (path
+ 2 <= end
&& isdirsep(path
[0]) && isdirsep(path
[1])) {
3403 while (path
< end
&& isdirsep(*path
)) path
++;
3404 if ((path
= rb_enc_path_next(path
, end
, enc
)) < end
&& path
[0] && path
[1] && !isdirsep(path
[1]))
3405 path
= rb_enc_path_next(path
+ 1, end
, enc
);
3406 return (char *)path
;
3409 #ifdef DOSISH_DRIVE_LETTER
3410 if (has_drive_letter(path
))
3411 return (char *)(path
+ 2);
3414 return (char *)path
;
3417 static inline char *
3418 skipprefixroot(const char *path
, const char *end
, rb_encoding
*enc
)
3420 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3421 char *p
= skipprefix(path
, end
, enc
);
3422 while (isdirsep(*p
)) p
++;
3425 return skiproot(path
, end
, enc
);
3429 #define strrdirsep rb_enc_path_last_separator
3431 rb_enc_path_last_separator(const char *path
, const char *end
, rb_encoding
*enc
)
3434 while (path
< end
) {
3435 if (isdirsep(*path
)) {
3436 const char *tmp
= path
++;
3437 while (path
< end
&& isdirsep(*path
)) path
++;
3438 if (path
>= end
) break;
3442 Inc(path
, end
, enc
);
3449 chompdirsep(const char *path
, const char *end
, rb_encoding
*enc
)
3451 while (path
< end
) {
3452 if (isdirsep(*path
)) {
3453 const char *last
= path
++;
3454 while (path
< end
&& isdirsep(*path
)) path
++;
3455 if (path
>= end
) return (char *)last
;
3458 Inc(path
, end
, enc
);
3461 return (char *)path
;
3465 rb_enc_path_end(const char *path
, const char *end
, rb_encoding
*enc
)
3467 if (path
< end
&& isdirsep(*path
)) path
++;
3468 return chompdirsep(path
, end
, enc
);
3471 static rb_encoding
*
3472 fs_enc_check(VALUE path1
, VALUE path2
)
3474 rb_encoding
*enc
= rb_enc_check(path1
, path2
);
3475 int encidx
= rb_enc_to_index(enc
);
3476 if (encidx
== ENCINDEX_US_ASCII
) {
3477 encidx
= rb_enc_get_index(path1
);
3478 if (encidx
== ENCINDEX_US_ASCII
)
3479 encidx
= rb_enc_get_index(path2
);
3480 enc
= rb_enc_from_index(encidx
);
3487 ntfs_tail(const char *path
, const char *end
, rb_encoding
*enc
)
3489 while (path
< end
&& *path
== '.') path
++;
3490 while (path
< end
&& !isADS(*path
)) {
3491 if (istrailinggarbage(*path
)) {
3492 const char *last
= path
++;
3493 while (path
< end
&& istrailinggarbage(*path
)) path
++;
3494 if (path
>= end
|| isADS(*path
)) return (char *)last
;
3496 else if (isdirsep(*path
)) {
3497 const char *last
= path
++;
3498 while (path
< end
&& isdirsep(*path
)) path
++;
3499 if (path
>= end
) return (char *)last
;
3500 if (isADS(*path
)) path
++;
3503 Inc(path
, end
, enc
);
3506 return (char *)path
;
3510 #define BUFCHECK(cond) do {\
3513 do {buflen *= 2;} while (cond);\
3514 rb_str_resize(result, buflen);\
3515 buf = RSTRING_PTR(result);\
3517 pend = buf + buflen;\
3521 #define BUFINIT() (\
3522 p = buf = RSTRING_PTR(result),\
3523 buflen = RSTRING_LEN(result),\
3527 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3529 # define SKIPPATHSEP(p) 1
3532 #define BUFCOPY(srcptr, srclen) do { \
3533 const int skip = SKIPPATHSEP(p); \
3534 rb_str_set_len(result, p-buf+skip); \
3535 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
3537 memcpy(p, (srcptr), (srclen)); \
3541 #define WITH_ROOTDIFF(stmt) do { \
3542 long rootdiff = root - buf; \
3544 root = buf + rootdiff; \
3548 copy_home_path(VALUE result
, const char *dir
)
3551 #if defined DOSISH || defined __CYGWIN__
3558 dirlen
= strlen(dir
);
3559 rb_str_resize(result
, dirlen
);
3560 memcpy(buf
= RSTRING_PTR(result
), dir
, dirlen
);
3561 encidx
= rb_filesystem_encindex();
3562 rb_enc_associate_index(result
, encidx
);
3563 #if defined DOSISH || defined __CYGWIN__
3564 enc
= rb_enc_from_index(encidx
);
3565 for (bend
= (p
= buf
) + dirlen
; p
< bend
; Inc(p
, bend
, enc
)) {
3575 rb_home_dir_of(VALUE user
, VALUE result
)
3578 struct passwd
*pwPtr
;
3580 extern char *getlogin(void);
3581 const char *pwPtr
= 0;
3582 # define endpwent() ((void)0)
3584 const char *dir
, *username
= RSTRING_PTR(user
);
3585 rb_encoding
*enc
= rb_enc_get(user
);
3587 rb_encoding
*fsenc
= rb_utf8_encoding();
3589 rb_encoding
*fsenc
= rb_filesystem_encoding();
3592 dir
= username
= RSTRING_PTR(rb_str_conv_enc(user
, enc
, fsenc
));
3596 pwPtr
= getpwnam(username
);
3598 if (strcasecmp(username
, getlogin()) == 0)
3599 dir
= pwPtr
= getenv("HOME");
3603 rb_raise(rb_eArgError
, "user %"PRIsVALUE
" doesn't exist", user
);
3606 dir
= pwPtr
->pw_dir
;
3608 copy_home_path(result
, dir
);
3615 rb_default_home_dir(VALUE result
)
3617 const char *dir
= getenv("HOME");
3619 #if defined HAVE_PWD_H
3621 /* We'll look up the user's default home dir in the password db by
3622 * login name, if possible, and failing that will fall back to looking
3623 * the information up by uid (as would be needed for processes that
3624 * are not a descendant of login(1) or a work-alike).
3626 * While the lookup by uid is more likely to succeed (since we always
3627 * have a uid, but may or may not have a login name), we prefer first
3628 * looking up by name to accommodate the possibility of multiple login
3629 * names (each with its own record in the password database, so each
3630 * with a potentially different home directory) being mapped to the
3631 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
3633 VALUE login_name
= rb_getlogin();
3635 # if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
3636 /* This is a corner case, but for backward compatibility reasons we
3637 * want to emit this error if neither the lookup by login name nor
3638 * lookup by getuid() has a chance of succeeding.
3640 if (NIL_P(login_name
)) {
3641 rb_raise(rb_eArgError
, "couldn't find login name -- expanding `~'");
3645 VALUE pw_dir
= rb_getpwdirnam_for_login(login_name
);
3646 if (NIL_P(pw_dir
)) {
3647 pw_dir
= rb_getpwdiruid();
3648 if (NIL_P(pw_dir
)) {
3649 rb_raise(rb_eArgError
, "couldn't find home for uid `%ld'", (long)getuid());
3654 copy_home_path(result
, RSTRING_PTR(pw_dir
));
3655 rb_str_resize(pw_dir
, 0);
3660 rb_raise(rb_eArgError
, "couldn't find HOME environment -- expanding `~'");
3662 return copy_home_path(result
, dir
);
3666 ospath_new(const char *ptr
, long len
, rb_encoding
*fsenc
)
3668 #if NORMALIZE_UTF8PATH
3669 VALUE path
= rb_str_normalize_ospath(ptr
, len
);
3670 rb_enc_associate(path
, fsenc
);
3673 return rb_enc_str_new(ptr
, len
, fsenc
);
3678 append_fspath(VALUE result
, VALUE fname
, char *dir
, rb_encoding
**enc
, rb_encoding
*fsenc
)
3680 char *buf
, *cwdp
= dir
;
3681 VALUE dirname
= Qnil
;
3682 size_t dirlen
= strlen(dir
), buflen
= rb_str_capacity(result
);
3684 if (NORMALIZE_UTF8PATH
|| *enc
!= fsenc
) {
3685 rb_encoding
*direnc
= fs_enc_check(fname
, dirname
= ospath_new(dir
, dirlen
, fsenc
));
3686 if (direnc
!= fsenc
) {
3687 dirname
= rb_str_conv_enc(dirname
, fsenc
, direnc
);
3688 RSTRING_GETMEM(dirname
, cwdp
, dirlen
);
3690 else if (NORMALIZE_UTF8PATH
) {
3691 RSTRING_GETMEM(dirname
, cwdp
, dirlen
);
3695 do {buflen
*= 2;} while (dirlen
> buflen
);
3696 rb_str_resize(result
, buflen
);
3697 buf
= RSTRING_PTR(result
);
3698 memcpy(buf
, cwdp
, dirlen
);
3700 if (!NIL_P(dirname
)) rb_str_resize(dirname
, 0);
3701 rb_enc_associate(result
, *enc
);
3702 return buf
+ dirlen
;
3706 rb_file_expand_path_internal(VALUE fname
, VALUE dname
, int abs_mode
, int long_name
, VALUE result
)
3708 const char *s
, *b
, *fend
;
3709 char *buf
, *p
, *pend
, *root
;
3710 size_t buflen
, bdiff
;
3711 rb_encoding
*enc
, *fsenc
= rb_filesystem_encoding();
3713 s
= StringValuePtr(fname
);
3714 fend
= s
+ RSTRING_LEN(fname
);
3715 enc
= rb_enc_get(fname
);
3718 if (s
[0] == '~' && abs_mode
== 0) { /* execute only if NOT absolute_path() */
3720 if (isdirsep(s
[1]) || s
[1] == '\0') {
3723 rb_str_set_len(result
, 0);
3725 rb_default_home_dir(result
);
3728 s
= nextdirsep(b
= s
, fend
, enc
);
3729 b
++; /* b[0] is '~' */
3731 BUFCHECK(bdiff
+ userlen
>= buflen
);
3732 memcpy(p
, b
, userlen
);
3733 ENC_CODERANGE_CLEAR(result
);
3734 rb_str_set_len(result
, userlen
);
3735 rb_enc_associate(result
, enc
);
3736 rb_home_dir_of(result
, result
);
3740 if (!rb_is_absolute_path(RSTRING_PTR(result
))) {
3742 rb_enc_raise(enc
, rb_eArgError
, "non-absolute home of %.*s%.0"PRIsVALUE
,
3743 (int)userlen
, b
, fname
);
3746 rb_raise(rb_eArgError
, "non-absolute home");
3752 #ifdef DOSISH_DRIVE_LETTER
3753 /* skip drive letter */
3754 else if (has_drive_letter(s
)) {
3755 if (isdirsep(s
[2])) {
3756 /* specified drive letter, and full path */
3757 /* skip drive letter */
3758 BUFCHECK(bdiff
+ 2 >= buflen
);
3762 rb_enc_copy(result
, fname
);
3765 /* specified drive, but not full path */
3767 if (!NIL_P(dname
) && !not_same_drive(dname
, s
[0])) {
3768 rb_file_expand_path_internal(dname
, Qnil
, abs_mode
, long_name
, result
);
3770 if (has_drive_letter(p
) && TOLOWER(p
[0]) == TOLOWER(s
[0])) {
3771 /* ok, same drive */
3776 char *e
= append_fspath(result
, fname
, getcwdofdrv(*s
), &enc
, fsenc
);
3781 rb_enc_associate(result
, enc
= fs_enc_check(result
, fname
));
3784 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
3789 else if (!rb_is_absolute_path(s
)) {
3790 if (!NIL_P(dname
)) {
3791 rb_file_expand_path_internal(dname
, Qnil
, abs_mode
, long_name
, result
);
3792 rb_enc_associate(result
, fs_enc_check(result
, fname
));
3797 char *e
= append_fspath(result
, fname
, ruby_getcwd(), &enc
, fsenc
);
3801 #if defined DOSISH || defined __CYGWIN__
3803 /* specified full path, but not drive letter nor UNC */
3804 /* we need to get the drive letter or UNC share name */
3805 p
= skipprefix(buf
, p
, enc
);
3809 p
= chompdirsep(skiproot(buf
, p
, enc
), p
, enc
);
3814 do s
++; while (isdirsep(*s
));
3817 BUFCHECK(bdiff
>= buflen
);
3818 memset(buf
, '/', len
);
3819 rb_str_set_len(result
, len
);
3820 rb_enc_associate(result
, fs_enc_check(result
, fname
));
3822 if (p
> buf
&& p
[-1] == '/')
3825 rb_str_set_len(result
, p
-buf
);
3826 BUFCHECK(bdiff
+ 1 >= buflen
);
3830 rb_str_set_len(result
, p
-buf
+1);
3831 BUFCHECK(bdiff
+ 1 >= buflen
);
3833 root
= skipprefix(buf
, p
+1, enc
);
3839 if (b
== s
++) { /* beginning of path element */
3845 if (*(s
+1) == '\0' || isdirsep(*(s
+1))) {
3846 /* We must go back to the parent */
3849 if (!(n
= strrdirsep(root
, p
, enc
))) {
3859 do ++s
; while (istrailinggarbage(*s
));
3864 #if defined DOSISH || defined __CYGWIN__
3870 /* ordinary path element, beginning don't move */
3879 while (s
< fend
&& istrailinggarbage(*s
)) s
++;
3889 #if defined DOSISH || defined __CYGWIN__
3893 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
3901 int n
= ignored_char_p(s
, fend
, enc
);
3904 WITH_ROOTDIFF(BUFCOPY(b
, s
-b
));
3920 static const char prime
[] = ":$DATA";
3921 enum {prime_len
= sizeof(prime
) -1};
3925 if (s
> b
+ prime_len
&& strncasecmp(s
- prime_len
, prime
, prime_len
) == 0) {
3926 /* alias of stream */
3927 /* get rid of a bug of x64 VC++ */
3928 if (isADS(*(s
- (prime_len
+1)))) {
3929 s
-= prime_len
+ 1; /* prime */
3931 else if (memchr(b
, ':', s
- prime_len
- b
)) {
3932 s
-= prime_len
; /* alternative */
3938 rb_str_set_len(result
, p
-buf
);
3940 if (p
== skiproot(buf
, p
+ !!*p
, enc
) - 1) p
++;
3944 if ((s
= strrdirsep(b
= buf
, p
, enc
)) != 0 && !strpbrk(s
, "*?")) {
3949 WIN32_FIND_DATAW wfd
;
3952 #ifdef HAVE_CYGWIN_CONV_PATH
3953 char *w32buf
= NULL
;
3954 const int flags
= CCP_POSIX_TO_WIN_A
| CCP_RELATIVE
;
3956 char w32buf
[MAXPATHLEN
];
3960 int lnk_added
= 0, is_symlink
= 0;
3964 if (lstat_without_gvl(buf
, &st
) == 0 && S_ISLNK(st
.st_mode
)) {
3966 if (len
> 4 && STRCASECMP(p
+ len
- 4, ".lnk") != 0) {
3970 path
= *buf
? buf
: "/";
3971 #ifdef HAVE_CYGWIN_CONV_PATH
3972 bufsize
= cygwin_conv_path(flags
, path
, NULL
, 0);
3975 if (lnk_added
) bufsize
+= 4;
3976 w32buf
= ALLOCA_N(char, bufsize
);
3977 if (cygwin_conv_path(flags
, path
, w32buf
, bufsize
) == 0) {
3982 bufsize
= MAXPATHLEN
;
3983 if (cygwin_conv_to_win32_path(path
, w32buf
) == 0) {
3987 if (is_symlink
&& b
== w32buf
) {
3989 strlcat(w32buf
, p
, bufsize
);
3991 strlcat(w32buf
, ".lnk", bufsize
);
3999 rb_str_set_len(result
, p
- buf
+ strlen(p
));
4000 encidx
= ENCODING_GET(result
);
4002 if (encidx
!= ENCINDEX_UTF_8
&& rb_enc_str_coderange(result
) != ENC_CODERANGE_7BIT
) {
4003 tmp
= rb_str_encode_ospath(result
);
4005 len
= MultiByteToWideChar(CP_UTF8
, 0, RSTRING_PTR(tmp
), -1, NULL
, 0);
4006 wstr
= ALLOCV_N(WCHAR
, v
, len
);
4007 MultiByteToWideChar(CP_UTF8
, 0, RSTRING_PTR(tmp
), -1, wstr
, len
);
4008 if (tmp
!= result
) rb_str_set_len(tmp
, 0);
4009 h
= FindFirstFileW(wstr
, &wfd
);
4011 if (h
!= INVALID_HANDLE_VALUE
) {
4014 len
= lstrlenW(wfd
.cFileName
);
4016 if (lnk_added
&& len
> 4 &&
4017 wcscasecmp(wfd
.cFileName
+ len
- 4, L
".lnk") == 0) {
4018 wfd
.cFileName
[len
-= 4] = L
'\0';
4025 len
= WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, NULL
, 0, NULL
, NULL
);
4026 if (tmp
== result
) {
4027 BUFCHECK(bdiff
+ len
>= buflen
);
4028 WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, p
, len
+ 1, NULL
, NULL
);
4031 rb_str_modify_expand(tmp
, len
);
4032 WideCharToMultiByte(CP_UTF8
, 0, wfd
.cFileName
, wlen
, RSTRING_PTR(tmp
), len
+ 1, NULL
, NULL
);
4033 rb_str_cat_conv_enc_opts(result
, bdiff
, RSTRING_PTR(tmp
), len
,
4034 rb_utf8_encoding(), 0, Qnil
);
4036 rb_str_resize(tmp
, 0);
4048 rb_str_set_len(result
, p
- buf
);
4049 rb_enc_check(fname
, result
);
4050 ENC_CODERANGE_CLEAR(result
);
4055 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, MAXPATHLEN + 2)
4058 str_shrink(VALUE str
)
4060 rb_str_resize(str
, RSTRING_LEN(str
));
4064 #define expand_path(fname, dname, abs_mode, long_name, result) \
4065 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
4067 #define check_expand_path_args(fname, dname) \
4068 (((fname) = rb_get_path(fname)), \
4069 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
4072 file_expand_path_1(VALUE fname
)
4074 return rb_file_expand_path_internal(fname
, Qnil
, 0, 0, EXPAND_PATH_BUFFER());
4078 rb_file_expand_path(VALUE fname
, VALUE dname
)
4080 check_expand_path_args(fname
, dname
);
4081 return expand_path(fname
, dname
, 0, 1, EXPAND_PATH_BUFFER());
4085 rb_file_expand_path_fast(VALUE fname
, VALUE dname
)
4087 return expand_path(fname
, dname
, 0, 0, EXPAND_PATH_BUFFER());
4091 rb_file_s_expand_path(int argc
, const VALUE
*argv
)
4093 rb_check_arity(argc
, 1, 2);
4094 return rb_file_expand_path(argv
[0], argc
> 1 ? argv
[1] : Qnil
);
4099 * File.expand_path(file_name [, dir_string] ) -> abs_file_name
4101 * Converts a pathname to an absolute pathname. Relative paths are
4102 * referenced from the current working directory of the process unless
4103 * +dir_string+ is given, in which case it will be used as the
4104 * starting point. The given pathname may start with a
4105 * ``<code>~</code>'', which expands to the process owner's home
4106 * directory (the environment variable +HOME+ must be set
4107 * correctly). ``<code>~</code><i>user</i>'' expands to the named
4108 * user's home directory.
4110 * File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
4112 * A simple example of using +dir_string+ is as follows.
4113 * File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
4115 * A more complex example which also resolves parent directory is as follows.
4116 * Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
4118 * File.expand_path("../../lib/mygem.rb", __FILE__)
4119 * #=> ".../path/to/project/lib/mygem.rb"
4121 * So first it resolves the parent of __FILE__, that is bin/, then go to the
4122 * parent, the root of the project and appends +lib/mygem.rb+.
4126 s_expand_path(int c
, const VALUE
* v
, VALUE _
)
4128 return rb_file_s_expand_path(c
, v
);
4132 rb_file_absolute_path(VALUE fname
, VALUE dname
)
4134 check_expand_path_args(fname
, dname
);
4135 return expand_path(fname
, dname
, 1, 1, EXPAND_PATH_BUFFER());
4139 rb_file_s_absolute_path(int argc
, const VALUE
*argv
)
4141 rb_check_arity(argc
, 1, 2);
4142 return rb_file_absolute_path(argv
[0], argc
> 1 ? argv
[1] : Qnil
);
4147 * File.absolute_path(file_name [, dir_string] ) -> abs_file_name
4149 * Converts a pathname to an absolute pathname. Relative paths are
4150 * referenced from the current working directory of the process unless
4151 * <i>dir_string</i> is given, in which case it will be used as the
4152 * starting point. If the given pathname starts with a ``<code>~</code>''
4153 * it is NOT expanded, it is treated as a normal directory name.
4155 * File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4159 s_absolute_path(int c
, const VALUE
* v
, VALUE _
)
4161 return rb_file_s_absolute_path(c
, v
);
4166 * File.absolute_path?(file_name) -> true or false
4168 * Returns <code>true</code> if +file_name+ is an absolute path, and
4169 * <code>false</code> otherwise.
4171 * File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4175 s_absolute_path_p(VALUE klass
, VALUE fname
)
4177 VALUE path
= rb_get_path(fname
);
4179 if (!rb_is_absolute_path(RSTRING_PTR(path
))) return Qfalse
;
4183 enum rb_realpath_mode
{
4187 RB_REALPATH_MODE_MAX
4191 realpath_rec(long *prefixlenp
, VALUE
*resolvedp
, const char *unresolved
, VALUE fallback
,
4192 VALUE loopcheck
, enum rb_realpath_mode mode
, int last
)
4194 const char *pend
= unresolved
+ strlen(unresolved
);
4195 rb_encoding
*enc
= rb_enc_get(*resolvedp
);
4197 CONST_ID(resolving
, "resolving");
4198 while (unresolved
< pend
) {
4199 const char *testname
= unresolved
;
4200 const char *unresolved_firstsep
= rb_enc_path_next(unresolved
, pend
, enc
);
4201 long testnamelen
= unresolved_firstsep
- unresolved
;
4202 const char *unresolved_nextname
= unresolved_firstsep
;
4203 while (unresolved_nextname
< pend
&& isdirsep(*unresolved_nextname
))
4204 unresolved_nextname
++;
4205 unresolved
= unresolved_nextname
;
4206 if (testnamelen
== 1 && testname
[0] == '.') {
4208 else if (testnamelen
== 2 && testname
[0] == '.' && testname
[1] == '.') {
4209 if (*prefixlenp
< RSTRING_LEN(*resolvedp
)) {
4210 const char *resolved_str
= RSTRING_PTR(*resolvedp
);
4211 const char *resolved_names
= resolved_str
+ *prefixlenp
;
4212 const char *lastsep
= strrdirsep(resolved_names
, resolved_str
+ RSTRING_LEN(*resolvedp
), enc
);
4213 long len
= lastsep
? lastsep
- resolved_names
: 0;
4214 rb_str_resize(*resolvedp
, *prefixlenp
+ len
);
4219 VALUE testpath
= rb_str_dup(*resolvedp
);
4220 if (*prefixlenp
< RSTRING_LEN(testpath
))
4221 rb_str_cat2(testpath
, "/");
4222 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4223 if (*prefixlenp
> 1 && *prefixlenp
== RSTRING_LEN(testpath
)) {
4224 const char *prefix
= RSTRING_PTR(testpath
);
4225 const char *last
= rb_enc_left_char_head(prefix
, prefix
+ *prefixlenp
- 1, prefix
+ *prefixlenp
, enc
);
4226 if (!isdirsep(*last
)) rb_str_cat2(testpath
, "/");
4229 rb_str_cat(testpath
, testname
, testnamelen
);
4230 checkval
= rb_hash_aref(loopcheck
, testpath
);
4231 if (!NIL_P(checkval
)) {
4232 if (checkval
== ID2SYM(resolving
)) {
4233 if (mode
== RB_REALPATH_CHECK
) {
4237 rb_syserr_fail_path(ELOOP
, testpath
);
4240 *resolvedp
= rb_str_dup(checkval
);
4246 ret
= lstat_without_gvl(RSTRING_PTR(testpath
), &sbuf
);
4249 if (e
== ENOENT
&& !NIL_P(fallback
)) {
4250 if (stat_without_gvl(RSTRING_PTR(fallback
), &sbuf
) == 0) {
4251 rb_str_replace(*resolvedp
, fallback
);
4255 if (mode
== RB_REALPATH_CHECK
) return -1;
4257 if (mode
== RB_REALPATH_STRICT
|| !last
|| *unresolved_firstsep
)
4258 rb_syserr_fail_path(e
, testpath
);
4259 *resolvedp
= testpath
;
4263 rb_syserr_fail_path(e
, testpath
);
4266 #ifdef HAVE_READLINK
4267 if (S_ISLNK(sbuf
.st_mode
)) {
4269 VALUE link_orig
= Qnil
;
4270 const char *link_prefix
, *link_names
;
4271 long link_prefixlen
;
4272 rb_hash_aset(loopcheck
, testpath
, ID2SYM(resolving
));
4273 link
= rb_readlink(testpath
, enc
);
4274 link_prefix
= RSTRING_PTR(link
);
4275 link_names
= skipprefixroot(link_prefix
, link_prefix
+ RSTRING_LEN(link
), rb_enc_get(link
));
4276 link_prefixlen
= link_names
- link_prefix
;
4277 if (link_prefixlen
> 0) {
4278 rb_encoding
*tmpenc
, *linkenc
= rb_enc_get(link
);
4280 link
= rb_str_subseq(link
, 0, link_prefixlen
);
4281 tmpenc
= fs_enc_check(*resolvedp
, link
);
4282 if (tmpenc
!= linkenc
) link
= rb_str_conv_enc(link
, linkenc
, tmpenc
);
4284 *prefixlenp
= link_prefixlen
;
4286 if (realpath_rec(prefixlenp
, resolvedp
, link_names
, testpath
,
4287 loopcheck
, mode
, !*unresolved_firstsep
))
4289 RB_GC_GUARD(link_orig
);
4290 rb_hash_aset(loopcheck
, testpath
, rb_str_dup_frozen(*resolvedp
));
4295 VALUE s
= rb_str_dup_frozen(testpath
);
4296 rb_hash_aset(loopcheck
, s
, s
);
4297 *resolvedp
= testpath
;
4306 rb_check_realpath_emulate(VALUE basedir
, VALUE path
, rb_encoding
*origenc
, enum rb_realpath_mode mode
)
4310 VALUE unresolved_path
;
4312 VALUE curdir
= Qnil
;
4315 char *path_names
= NULL
, *basedir_names
= NULL
, *curdir_names
= NULL
;
4316 char *ptr
, *prefixptr
= NULL
, *pend
;
4319 unresolved_path
= rb_str_dup_frozen(path
);
4321 if (!NIL_P(basedir
)) {
4322 FilePathValue(basedir
);
4323 basedir
= TO_OSPATH(rb_str_dup_frozen(basedir
));
4326 enc
= rb_enc_get(unresolved_path
);
4327 unresolved_path
= TO_OSPATH(unresolved_path
);
4328 RSTRING_GETMEM(unresolved_path
, ptr
, len
);
4329 path_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(unresolved_path
));
4330 if (ptr
!= path_names
) {
4331 resolved
= rb_str_subseq(unresolved_path
, 0, path_names
- ptr
);
4335 if (!NIL_P(basedir
)) {
4336 RSTRING_GETMEM(basedir
, ptr
, len
);
4337 basedir_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(basedir
));
4338 if (ptr
!= basedir_names
) {
4339 resolved
= rb_str_subseq(basedir
, 0, basedir_names
- ptr
);
4344 curdir
= rb_dir_getwd_ospath();
4345 RSTRING_GETMEM(curdir
, ptr
, len
);
4346 curdir_names
= skipprefixroot(ptr
, ptr
+ len
, rb_enc_get(curdir
));
4347 resolved
= rb_str_subseq(curdir
, 0, curdir_names
- ptr
);
4350 RSTRING_GETMEM(resolved
, prefixptr
, prefixlen
);
4351 pend
= prefixptr
+ prefixlen
;
4352 ptr
= chompdirsep(prefixptr
, pend
, enc
);
4354 prefixlen
= ++ptr
- prefixptr
;
4355 rb_str_set_len(resolved
, prefixlen
);
4357 #ifdef FILE_ALT_SEPARATOR
4358 while (prefixptr
< ptr
) {
4359 if (*prefixptr
== FILE_ALT_SEPARATOR
) {
4362 Inc(prefixptr
, pend
, enc
);
4366 switch (rb_enc_to_index(enc
)) {
4367 case ENCINDEX_ASCII
:
4368 case ENCINDEX_US_ASCII
:
4369 rb_enc_associate_index(resolved
, rb_filesystem_encindex());
4372 loopcheck
= rb_hash_new();
4374 if (realpath_rec(&prefixlen
, &resolved
, curdir_names
, Qnil
, loopcheck
, mode
, 0))
4377 if (basedir_names
) {
4378 if (realpath_rec(&prefixlen
, &resolved
, basedir_names
, Qnil
, loopcheck
, mode
, 0))
4381 if (realpath_rec(&prefixlen
, &resolved
, path_names
, Qnil
, loopcheck
, mode
, 1))
4384 if (origenc
&& origenc
!= rb_enc_get(resolved
)) {
4385 if (rb_enc_str_asciionly_p(resolved
)) {
4386 rb_enc_associate(resolved
, origenc
);
4389 resolved
= rb_str_conv_enc(resolved
, NULL
, origenc
);
4393 RB_GC_GUARD(unresolved_path
);
4394 RB_GC_GUARD(curdir
);
4398 static VALUE
rb_file_join(VALUE ary
);
4400 #ifndef HAVE_REALPATH
4402 rb_check_realpath_emulate_try(VALUE arg
)
4404 VALUE
*args
= (VALUE
*)arg
;
4405 return rb_check_realpath_emulate(args
[0], args
[1], (rb_encoding
*)args
[2], RB_REALPATH_CHECK
);
4409 rb_check_realpath_emulate_rescue(VALUE arg
, VALUE exc
)
4413 #endif /* HAVE_REALPATH */
4416 rb_check_realpath_internal(VALUE basedir
, VALUE path
, rb_encoding
*origenc
, enum rb_realpath_mode mode
)
4418 #ifdef HAVE_REALPATH
4419 VALUE unresolved_path
;
4420 char *resolved_ptr
= NULL
;
4423 if (mode
== RB_REALPATH_DIR
) {
4424 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4427 unresolved_path
= rb_str_dup_frozen(path
);
4428 if (*RSTRING_PTR(unresolved_path
) != '/' && !NIL_P(basedir
)) {
4429 unresolved_path
= rb_file_join(rb_assoc_new(basedir
, unresolved_path
));
4431 if (origenc
) unresolved_path
= TO_OSPATH(unresolved_path
);
4433 if ((resolved_ptr
= realpath(RSTRING_PTR(unresolved_path
), NULL
)) == NULL
) {
4434 /* glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4435 returning ENOTDIR in that case.
4436 glibc realpath(3) can also return ENOENT for paths that exist,
4438 Fallback to the emulated approach in either of those cases. */
4439 if (errno
== ENOTDIR
||
4440 (errno
== ENOENT
&& rb_file_exist_p(0, unresolved_path
))) {
4441 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4444 if (mode
== RB_REALPATH_CHECK
) {
4447 rb_sys_fail_path(unresolved_path
);
4449 resolved
= ospath_new(resolved_ptr
, strlen(resolved_ptr
), rb_filesystem_encoding());
4452 # if !defined(__LINUX__) && !defined(__APPLE__)
4453 /* As `resolved` is a String in the filesystem encoding, no
4454 * conversion is needed */
4456 if (stat_without_gvl(RSTRING_PTR(resolved
), &st
) < 0) {
4457 if (mode
== RB_REALPATH_CHECK
) {
4460 rb_sys_fail_path(unresolved_path
);
4464 if (origenc
&& origenc
!= rb_enc_get(resolved
)) {
4465 if (!rb_enc_str_asciionly_p(resolved
)) {
4466 resolved
= rb_str_conv_enc(resolved
, NULL
, origenc
);
4468 rb_enc_associate(resolved
, origenc
);
4471 if (rb_enc_str_coderange(resolved
) == ENC_CODERANGE_BROKEN
) {
4472 rb_enc_associate(resolved
, rb_filesystem_encoding());
4473 if (rb_enc_str_coderange(resolved
) == ENC_CODERANGE_BROKEN
) {
4474 rb_enc_associate(resolved
, rb_ascii8bit_encoding());
4478 RB_GC_GUARD(unresolved_path
);
4481 if (mode
== RB_REALPATH_CHECK
) {
4485 arg
[2] = (VALUE
)origenc
;
4487 return rb_rescue(rb_check_realpath_emulate_try
, (VALUE
)arg
,
4488 rb_check_realpath_emulate_rescue
, Qnil
);
4491 return rb_check_realpath_emulate(basedir
, path
, origenc
, mode
);
4493 #endif /* HAVE_REALPATH */
4497 rb_realpath_internal(VALUE basedir
, VALUE path
, int strict
)
4499 const enum rb_realpath_mode mode
=
4500 strict
? RB_REALPATH_STRICT
: RB_REALPATH_DIR
;
4501 return rb_check_realpath_internal(basedir
, path
, rb_enc_get(path
), mode
);
4505 rb_check_realpath(VALUE basedir
, VALUE path
, rb_encoding
*enc
)
4507 return rb_check_realpath_internal(basedir
, path
, enc
, RB_REALPATH_CHECK
);
4512 * File.realpath(pathname [, dir_string]) -> real_pathname
4514 * Returns the real (absolute) pathname of _pathname_ in the actual
4515 * filesystem not containing symlinks or useless dots.
4517 * If _dir_string_ is given, it is used as a base directory
4518 * for interpreting relative pathname instead of the current directory.
4520 * All components of the pathname must exist when this method is
4524 rb_file_s_realpath(int argc
, VALUE
*argv
, VALUE klass
)
4526 VALUE basedir
= (rb_check_arity(argc
, 1, 2) > 1) ? argv
[1] : Qnil
;
4527 VALUE path
= argv
[0];
4528 FilePathValue(path
);
4529 return rb_realpath_internal(basedir
, path
, 1);
4534 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4536 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4537 * The real pathname doesn't contain symlinks or useless dots.
4539 * If _dir_string_ is given, it is used as a base directory
4540 * for interpreting relative pathname instead of the current directory.
4542 * The last component of the real pathname can be nonexistent.
4545 rb_file_s_realdirpath(int argc
, VALUE
*argv
, VALUE klass
)
4547 VALUE basedir
= (rb_check_arity(argc
, 1, 2) > 1) ? argv
[1] : Qnil
;
4548 VALUE path
= argv
[0];
4549 FilePathValue(path
);
4550 return rb_realpath_internal(basedir
, path
, 0);
4554 rmext(const char *p
, long l0
, long l1
, const char *e
, long l2
, rb_encoding
*enc
)
4558 const char *s
, *last
;
4560 if (!e
|| !l2
) return 0;
4562 c
= rb_enc_codepoint_len(e
, e
+ l2
, &len1
, enc
);
4563 if (rb_enc_ascget(e
+ len1
, e
+ l2
, &len2
, enc
) == '*' && len1
+ len2
== l2
) {
4564 if (c
== '.') return l0
;
4569 if (rb_enc_codepoint_len(s
, e
, &len1
, enc
) == c
) last
= s
;
4574 if (l1
< l2
) return l1
;
4577 if (rb_enc_left_char_head(p
, s
, p
+l1
, enc
) != s
) return 0;
4578 #if CASEFOLD_FILESYSTEM
4579 #define fncomp strncasecmp
4581 #define fncomp strncmp
4583 if (fncomp(s
, e
, l2
) == 0) {
4590 ruby_enc_find_basename(const char *name
, long *baselen
, long *alllen
, rb_encoding
*enc
)
4592 const char *p
, *q
, *e
, *end
;
4593 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4598 end
= name
+ (alllen
? (size_t)*alllen
: strlen(name
));
4599 name
= skipprefix(name
, end
, enc
);
4600 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4603 while (isdirsep(*name
))
4608 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4612 #ifdef DOSISH_DRIVE_LETTER
4613 else if (*p
== ':') {
4626 if (!(p
= strrdirsep(name
, end
, enc
))) {
4630 while (isdirsep(*p
)) p
++; /* skip last / */
4633 n
= ntfs_tail(p
, end
, enc
) - p
;
4635 n
= chompdirsep(p
, end
, enc
) - p
;
4637 for (q
= p
; q
- p
< n
&& *q
== '.'; q
++);
4638 for (e
= 0; q
- p
< n
; Inc(q
, end
, enc
)) {
4639 if (*q
== '.') e
= q
;
4654 * File.basename(file_name [, suffix] ) -> base_name
4656 * Returns the last component of the filename given in
4657 * <i>file_name</i> (after first stripping trailing separators),
4658 * which can be formed using both File::SEPARATOR and
4659 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4660 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4661 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4662 * any extension will be removed.
4664 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4665 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4666 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4670 rb_file_s_basename(int argc
, VALUE
*argv
, VALUE _
)
4672 VALUE fname
, fext
, basename
;
4673 const char *name
, *p
;
4678 if (rb_check_arity(argc
, 1, 2) == 2) {
4681 enc
= check_path_encoding(fext
);
4684 FilePathStringValue(fname
);
4685 if (NIL_P(fext
) || !(enc
= rb_enc_compatible(fname
, fext
))) {
4686 enc
= rb_enc_get(fname
);
4689 if ((n
= RSTRING_LEN(fname
)) == 0 || !*(name
= RSTRING_PTR(fname
)))
4690 return rb_str_new_shared(fname
);
4692 p
= ruby_enc_find_basename(name
, &f
, &n
, enc
);
4699 fp
= StringValueCStr(fext
);
4700 if (!(f
= rmext(p
, f
, n
, fp
, RSTRING_LEN(fext
), enc
))) {
4705 if (f
== RSTRING_LEN(fname
)) return rb_str_new_shared(fname
);
4708 basename
= rb_str_new(p
, f
);
4709 rb_enc_copy(basename
, fname
);
4713 static VALUE
rb_file_dirname_n(VALUE fname
, int n
);
4717 * File.dirname(file_name, level = 1) -> dir_name
4719 * Returns all components of the filename given in <i>file_name</i>
4720 * except the last one (after first stripping trailing separators).
4721 * The filename can be formed using both File::SEPARATOR and
4722 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4723 * not <code>nil</code>.
4725 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4727 * If +level+ is given, removes the last +level+ components, not only
4730 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4731 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4735 rb_file_s_dirname(int argc
, VALUE
*argv
, VALUE klass
)
4738 if ((argc
= rb_check_arity(argc
, 1, 2)) > 1) {
4739 n
= NUM2INT(argv
[1]);
4741 return rb_file_dirname_n(argv
[0], n
);
4745 rb_file_dirname(VALUE fname
)
4747 return rb_file_dirname_n(fname
, 1);
4751 rb_file_dirname_n(VALUE fname
, int n
)
4753 const char *name
, *root
, *p
, *end
;
4759 if (n
< 0) rb_raise(rb_eArgError
, "negative level: %d", n
);
4760 FilePathStringValue(fname
);
4761 name
= StringValueCStr(fname
);
4762 end
= name
+ RSTRING_LEN(fname
);
4763 enc
= rb_enc_get(fname
);
4764 root
= skiproot(name
, end
, enc
);
4766 if (root
> name
+ 1 && isdirsep(*name
))
4767 root
= skipprefix(name
= root
- 2, end
, enc
);
4769 if (root
> name
+ 1)
4772 if (n
> (end
- root
+ 1) / 2) {
4782 if (!(p
= strrdirsep(root
, end
, enc
))) p
= root
;
4785 seps
= ALLOCV_N(const char *, sepsv
, n
);
4786 for (i
= 0; i
< n
; ++i
) seps
[i
] = root
;
4788 for (p
= root
; p
< end
; ) {
4790 const char *tmp
= p
++;
4791 while (p
< end
&& isdirsep(*p
)) p
++;
4792 if (p
>= end
) break;
4806 return rb_usascii_str_new2(".");
4807 #ifdef DOSISH_DRIVE_LETTER
4808 if (has_drive_letter(name
) && isdirsep(*(name
+ 2))) {
4809 const char *top
= skiproot(name
+ 2, end
, enc
);
4810 dirname
= rb_str_new(name
, 3);
4811 rb_str_cat(dirname
, top
, p
- top
);
4815 dirname
= rb_str_new(name
, p
- name
);
4816 #ifdef DOSISH_DRIVE_LETTER
4817 if (has_drive_letter(name
) && root
== name
+ 2 && p
- name
== 2)
4818 rb_str_cat(dirname
, ".", 1);
4820 rb_enc_copy(dirname
, fname
);
4825 * accept a String, and return the pointer of the extension.
4826 * if len is passed, set the length of extension to it.
4827 * returned pointer is in ``name'' or NULL.
4831 * end with dot dot 1
4832 * .ext dot len of .ext
4833 * .ext:stream dot len of .ext without :stream (NT only)
4837 ruby_enc_find_extname(const char *name
, long *len
, rb_encoding
*enc
)
4839 const char *p
, *e
, *end
= name
+ (len
? *len
: (long)strlen(name
));
4841 p
= strrdirsep(name
, end
, enc
); /* get the last path component */
4845 do name
= ++p
; while (isdirsep(*p
));
4848 while (*p
&& *p
== '.') p
++;
4850 if (*p
== '.' || istrailinggarbage(*p
)) {
4852 const char *last
= p
++, *dot
= last
;
4853 while (istrailinggarbage(*p
)) {
4854 if (*p
== '.') dot
= p
;
4857 if (!*p
|| isADS(*p
)) {
4861 if (*last
== '.' || dot
> last
) e
= dot
;
4864 e
= p
; /* get the last dot of the last component */
4868 else if (isADS(*p
)) {
4872 else if (isdirsep(*p
))
4878 /* no dot, or the only dot is first or end? */
4879 if (!e
|| e
== name
)
4891 * File.extname(path) -> string
4893 * Returns the extension (the portion of file name in +path+
4894 * starting from the last period).
4896 * If +path+ is a dotfile, or starts with a period, then the starting
4897 * dot is not dealt with the start of the extension.
4899 * An empty string will also be returned when the period is the last character
4902 * On Windows, trailing dots are truncated.
4904 * File.extname("test.rb") #=> ".rb"
4905 * File.extname("a/b/d/test.rb") #=> ".rb"
4906 * File.extname(".a/b/d/test.rb") #=> ".rb"
4907 * File.extname("foo.") #=> "" on Windows
4908 * File.extname("foo.") #=> "." on non-Windows
4909 * File.extname("test") #=> ""
4910 * File.extname(".profile") #=> ""
4911 * File.extname(".profile.sh") #=> ".sh"
4916 rb_file_s_extname(VALUE klass
, VALUE fname
)
4918 const char *name
, *e
;
4922 FilePathStringValue(fname
);
4923 name
= StringValueCStr(fname
);
4924 len
= RSTRING_LEN(fname
);
4925 e
= ruby_enc_find_extname(name
, &len
, rb_enc_get(fname
));
4927 return rb_str_new(0, 0);
4928 extname
= rb_str_subseq(fname
, e
- name
, len
); /* keep the dot, too! */
4934 * File.path(path) -> string
4936 * Returns the string representation of the path
4938 * File.path("/dev/null") #=> "/dev/null"
4939 * File.path(Pathname.new("/tmp")) #=> "/tmp"
4944 rb_file_s_path(VALUE klass
, VALUE fname
)
4946 return rb_get_path(fname
);
4951 * File.split(file_name) -> array
4953 * Splits the given string into a directory and a file component and
4954 * returns them in a two-element array. See also File::dirname and
4957 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
4961 rb_file_s_split(VALUE klass
, VALUE path
)
4963 FilePathStringValue(path
); /* get rid of converting twice */
4964 return rb_assoc_new(rb_file_dirname(path
), rb_file_s_basename(1,&path
,Qundef
));
4968 file_inspect_join(VALUE ary
, VALUE arg
, int recur
)
4970 if (recur
|| ary
== arg
) rb_raise(rb_eArgError
, "recursive array");
4971 return rb_file_join(arg
);
4975 rb_file_join(VALUE ary
)
4979 const char *name
, *tail
;
4983 if (RARRAY_LEN(ary
) == 0) return rb_str_new(0, 0);
4986 for (i
=0; i
<RARRAY_LEN(ary
); i
++) {
4987 tmp
= RARRAY_AREF(ary
, i
);
4988 if (RB_TYPE_P(tmp
, T_STRING
)) {
4989 check_path_encoding(tmp
);
4990 len
+= RSTRING_LEN(tmp
);
4996 len
+= RARRAY_LEN(ary
) - 1;
4997 result
= rb_str_buf_new(len
);
4998 RBASIC_CLEAR_CLASS(result
);
4999 for (i
=0; i
<RARRAY_LEN(ary
); i
++) {
5000 tmp
= RARRAY_AREF(ary
, i
);
5001 switch (OBJ_BUILTIN_TYPE(tmp
)) {
5003 if (!checked
) check_path_encoding(tmp
);
5004 StringValueCStr(tmp
);
5008 rb_raise(rb_eArgError
, "recursive array");
5011 tmp
= rb_exec_recursive(file_inspect_join
, ary
, tmp
);
5015 FilePathStringValue(tmp
);
5018 RSTRING_GETMEM(result
, name
, len
);
5020 rb_enc_copy(result
, tmp
);
5023 tail
= chompdirsep(name
, name
+ len
, rb_enc_get(result
));
5024 if (RSTRING_PTR(tmp
) && isdirsep(RSTRING_PTR(tmp
)[0])) {
5025 rb_str_set_len(result
, tail
- name
);
5028 rb_str_cat(result
, "/", 1);
5031 enc
= fs_enc_check(result
, tmp
);
5032 rb_str_buf_append(result
, tmp
);
5033 rb_enc_associate(result
, enc
);
5035 RBASIC_SET_CLASS_RAW(result
, rb_cString
);
5042 * File.join(string, ...) -> string
5044 * Returns a new string formed by joining the strings using
5047 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5052 rb_file_s_join(VALUE klass
, VALUE args
)
5054 return rb_file_join(args
);
5057 #if defined(HAVE_TRUNCATE) || defined(HAVE_CHSIZE)
5058 struct truncate_arg
{
5060 #if defined(HAVE_TRUNCATE)
5061 #define NUM2POS(n) NUM2OFFT(n)
5064 #define NUM2POS(n) NUM2LONG(n)
5070 nogvl_truncate(void *ptr
)
5072 struct truncate_arg
*ta
= ptr
;
5073 #ifdef HAVE_TRUNCATE
5074 return (void *)(VALUE
)truncate(ta
->path
, ta
->pos
);
5075 #else /* defined(HAVE_CHSIZE) */
5077 int tmpfd
= rb_cloexec_open(ta
->path
, 0, 0);
5081 rb_update_max_fd(tmpfd
);
5082 if (chsize(tmpfd
, ta
->pos
) < 0) {
5096 * File.truncate(file_name, integer) -> 0
5098 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5099 * bytes long. Not available on all platforms.
5101 * f = File.new("out", "w")
5102 * f.write("1234567890") #=> 10
5104 * File.truncate("out", 5) #=> 0
5105 * File.size("out") #=> 5
5110 rb_file_s_truncate(VALUE klass
, VALUE path
, VALUE len
)
5112 struct truncate_arg ta
;
5115 ta
.pos
= NUM2POS(len
);
5116 FilePathValue(path
);
5117 path
= rb_str_encode_ospath(path
);
5118 ta
.path
= StringValueCStr(path
);
5120 r
= (int)(VALUE
)rb_thread_call_without_gvl(nogvl_truncate
, &ta
,
5123 rb_sys_fail_path(path
);
5128 #define rb_file_s_truncate rb_f_notimplement
5131 #if defined(HAVE_FTRUNCATE) || defined(HAVE_CHSIZE)
5132 struct ftruncate_arg
{
5134 #if defined(HAVE_FTRUNCATE)
5135 #define NUM2POS(n) NUM2OFFT(n)
5138 #define NUM2POS(n) NUM2LONG(n)
5144 nogvl_ftruncate(void *ptr
)
5146 struct ftruncate_arg
*fa
= ptr
;
5148 #ifdef HAVE_FTRUNCATE
5149 return (VALUE
)ftruncate(fa
->fd
, fa
->pos
);
5150 #else /* defined(HAVE_CHSIZE) */
5151 return (VALUE
)chsize(fa
->fd
, fa
->pos
);
5157 * file.truncate(integer) -> 0
5159 * Truncates <i>file</i> to at most <i>integer</i> bytes. The file
5160 * must be opened for writing. Not available on all platforms.
5162 * f = File.new("out", "w")
5163 * f.syswrite("1234567890") #=> 10
5164 * f.truncate(5) #=> 0
5166 * File.size("out") #=> 5
5170 rb_file_truncate(VALUE obj
, VALUE len
)
5173 struct ftruncate_arg fa
;
5175 fa
.pos
= NUM2POS(len
);
5176 GetOpenFile(obj
, fptr
);
5177 if (!(fptr
->mode
& FMODE_WRITABLE
)) {
5178 rb_raise(rb_eIOError
, "not opened for writing");
5180 rb_io_flush_raw(obj
, 0);
5182 if ((int)rb_thread_io_blocking_region(nogvl_ftruncate
, &fa
, fa
.fd
) < 0) {
5183 rb_sys_fail_path(fptr
->pathv
);
5189 #define rb_file_truncate rb_f_notimplement
5206 #include <winerror.h>
5210 rb_thread_flock(void *data
)
5213 int old_errno
= errno
;
5215 int *op
= data
, ret
= flock(op
[0], op
[1]);
5218 if (GetLastError() == ERROR_NOT_LOCKED
) {
5228 * file.flock(locking_constant) -> 0 or false
5230 * Locks or unlocks a file according to <i>locking_constant</i> (a
5231 * logical <em>or</em> of the values in the table below).
5232 * Returns <code>false</code> if File::LOCK_NB is specified and the
5233 * operation would otherwise have blocked. Not available on all
5236 * Locking constants (in class File):
5238 * LOCK_EX | Exclusive lock. Only one process may hold an
5239 * | exclusive lock for a given file at a time.
5240 * ----------+------------------------------------------------
5241 * LOCK_NB | Don't block when locking. May be combined
5242 * | with other lock options using logical or.
5243 * ----------+------------------------------------------------
5244 * LOCK_SH | Shared lock. Multiple processes may each hold a
5245 * | shared lock for a given file at the same time.
5246 * ----------+------------------------------------------------
5251 * # update a counter using write lock
5252 * # don't use "w" because it truncates the file before lock.
5253 * File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
5254 * f.flock(File::LOCK_EX)
5255 * value = f.read.to_i + 1
5257 * f.write("#{value}\n")
5262 * # read the counter using read lock
5263 * File.open("counter", "r") {|f|
5264 * f.flock(File::LOCK_SH)
5271 rb_file_flock(VALUE obj
, VALUE operation
)
5275 struct timeval time
;
5277 op
[1] = op1
= NUM2INT(operation
);
5278 GetOpenFile(obj
, fptr
);
5281 if (fptr
->mode
& FMODE_WRITABLE
) {
5282 rb_io_flush_raw(obj
, 0);
5284 while ((int)rb_thread_io_blocking_region(rb_thread_flock
, op
, fptr
->fd
) < 0) {
5289 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5292 if (op1
& LOCK_NB
) return Qfalse
;
5295 time
.tv_usec
= 100 * 1000; /* 0.1 sec */
5296 rb_thread_wait_for(time
);
5297 rb_io_check_closed(fptr
);
5301 #if defined(ERESTART)
5307 rb_syserr_fail_path(e
, fptr
->pathv
);
5314 test_check(int n
, int argc
, VALUE
*argv
)
5319 rb_check_arity(argc
, n
, n
);
5320 for (i
=1; i
<n
; i
++) {
5321 if (!RB_TYPE_P(argv
[i
], T_FILE
)) {
5322 FilePathValue(argv
[i
]);
5327 #define CHECK(n) test_check((n), argc, argv)
5331 * test(cmd, file1 [, file2] ) -> obj
5333 * Uses the character +cmd+ to perform various tests on +file1+ (first
5334 * table below) or on +file1+ and +file2+ (second table).
5336 * File tests on a single file:
5338 * Cmd Returns Meaning
5339 * "A" | Time | Last access time for file1
5340 * "b" | boolean | True if file1 is a block device
5341 * "c" | boolean | True if file1 is a character device
5342 * "C" | Time | Last change time for file1
5343 * "d" | boolean | True if file1 exists and is a directory
5344 * "e" | boolean | True if file1 exists
5345 * "f" | boolean | True if file1 exists and is a regular file
5346 * "g" | boolean | True if file1 has the \CF{setgid} bit
5347 * | | set (false under NT)
5348 * "G" | boolean | True if file1 exists and has a group
5349 * | | ownership equal to the caller's group
5350 * "k" | boolean | True if file1 exists and has the sticky bit set
5351 * "l" | boolean | True if file1 exists and is a symbolic link
5352 * "M" | Time | Last modification time for file1
5353 * "o" | boolean | True if file1 exists and is owned by
5354 * | | the caller's effective uid
5355 * "O" | boolean | True if file1 exists and is owned by
5356 * | | the caller's real uid
5357 * "p" | boolean | True if file1 exists and is a fifo
5358 * "r" | boolean | True if file1 is readable by the effective
5359 * | | uid/gid of the caller
5360 * "R" | boolean | True if file is readable by the real
5361 * | | uid/gid of the caller
5362 * "s" | int/nil | If file1 has nonzero size, return the size,
5363 * | | otherwise return nil
5364 * "S" | boolean | True if file1 exists and is a socket
5365 * "u" | boolean | True if file1 has the setuid bit set
5366 * "w" | boolean | True if file1 exists and is writable by
5367 * | | the effective uid/gid
5368 * "W" | boolean | True if file1 exists and is writable by
5369 * | | the real uid/gid
5370 * "x" | boolean | True if file1 exists and is executable by
5371 * | | the effective uid/gid
5372 * "X" | boolean | True if file1 exists and is executable by
5373 * | | the real uid/gid
5374 * "z" | boolean | True if file1 exists and has a zero length
5376 * Tests that take two files:
5378 * "-" | boolean | True if file1 and file2 are identical
5379 * "=" | boolean | True if the modification times of file1
5380 * | | and file2 are equal
5381 * "<" | boolean | True if the modification time of file1
5382 * | | is prior to that of file2
5383 * ">" | boolean | True if the modification time of file1
5384 * | | is after that of file2
5388 rb_f_test(int argc
, VALUE
*argv
, VALUE _
)
5392 if (argc
== 0) rb_check_arity(argc
, 2, 3);
5393 cmd
= NUM2CHR(argv
[0]);
5397 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd
)) {
5401 return rb_file_blockdev_p(0, argv
[1]);
5404 return rb_file_chardev_p(0, argv
[1]);
5407 return rb_file_directory_p(0, argv
[1]);
5410 return rb_file_exist_p(0, argv
[1]);
5413 return rb_file_file_p(0, argv
[1]);
5416 return rb_file_sgid_p(0, argv
[1]);
5419 return rb_file_grpowned_p(0, argv
[1]);
5422 return rb_file_sticky_p(0, argv
[1]);
5425 return rb_file_symlink_p(0, argv
[1]);
5428 return rb_file_owned_p(0, argv
[1]);
5431 return rb_file_rowned_p(0, argv
[1]);
5434 return rb_file_pipe_p(0, argv
[1]);
5437 return rb_file_readable_p(0, argv
[1]);
5440 return rb_file_readable_real_p(0, argv
[1]);
5443 return rb_file_size_p(0, argv
[1]);
5446 return rb_file_socket_p(0, argv
[1]);
5449 return rb_file_suid_p(0, argv
[1]);
5452 return rb_file_writable_p(0, argv
[1]);
5455 return rb_file_writable_real_p(0, argv
[1]);
5458 return rb_file_executable_p(0, argv
[1]);
5461 return rb_file_executable_real_p(0, argv
[1]);
5464 return rb_file_zero_p(0, argv
[1]);
5468 if (strchr("MAC", cmd
)) {
5470 VALUE fname
= argv
[1];
5473 if (rb_stat(fname
, &st
) == -1) {
5475 FilePathValue(fname
);
5476 rb_syserr_fail_path(e
, fname
);
5481 return stat_atime(&st
);
5483 return stat_mtime(&st
);
5485 return stat_ctime(&st
);
5491 return rb_file_identical_p(0, argv
[1], argv
[2]);
5494 if (strchr("=<>", cmd
)) {
5495 struct stat st1
, st2
;
5496 struct timespec t1
, t2
;
5499 if (rb_stat(argv
[1], &st1
) < 0) return Qfalse
;
5500 if (rb_stat(argv
[2], &st2
) < 0) return Qfalse
;
5502 t1
= stat_mtimespec(&st1
);
5503 t2
= stat_mtimespec(&st2
);
5507 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
== t2
.tv_nsec
) return Qtrue
;
5511 if (t1
.tv_sec
> t2
.tv_sec
) return Qtrue
;
5512 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
> t2
.tv_nsec
) return Qtrue
;
5516 if (t1
.tv_sec
< t2
.tv_sec
) return Qtrue
;
5517 if (t1
.tv_sec
== t2
.tv_sec
&& t1
.tv_nsec
< t2
.tv_nsec
) return Qtrue
;
5522 /* unknown command */
5524 rb_raise(rb_eArgError
, "unknown command '%s%c'", cmd
== '\'' || cmd
== '\\' ? "\\" : "", cmd
);
5527 rb_raise(rb_eArgError
, "unknown command \"\\x%02X\"", cmd
);
5529 UNREACHABLE_RETURN(Qundef
);
5534 * Document-class: File::Stat
5536 * Objects of class File::Stat encapsulate common status information
5537 * for File objects. The information is recorded at the moment the
5538 * File::Stat object is created; changes made to the file after that
5539 * point will not be reflected. File::Stat objects are returned by
5540 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5541 * methods return platform-specific values, and not all values are
5542 * meaningful on all systems. See also Kernel#test.
5546 rb_stat_s_alloc(VALUE klass
)
5548 return stat_new_0(klass
, 0);
5554 * File::Stat.new(file_name) -> stat
5556 * Create a File::Stat object for the given file name (raising an
5557 * exception if the file doesn't exist).
5561 rb_stat_init(VALUE obj
, VALUE fname
)
5563 struct stat st
, *nst
;
5565 FilePathValue(fname
);
5566 fname
= rb_str_encode_ospath(fname
);
5567 if (STAT(StringValueCStr(fname
), &st
) == -1) {
5568 rb_sys_fail_path(fname
);
5570 if (DATA_PTR(obj
)) {
5571 xfree(DATA_PTR(obj
));
5572 DATA_PTR(obj
) = NULL
;
5574 nst
= ALLOC(struct stat
);
5576 DATA_PTR(obj
) = nst
;
5583 rb_stat_init_copy(VALUE copy
, VALUE orig
)
5587 if (!OBJ_INIT_COPY(copy
, orig
)) return copy
;
5588 if (DATA_PTR(copy
)) {
5589 xfree(DATA_PTR(copy
));
5592 if (DATA_PTR(orig
)) {
5593 nst
= ALLOC(struct stat
);
5594 *nst
= *(struct stat
*)DATA_PTR(orig
);
5595 DATA_PTR(copy
) = nst
;
5603 * stat.ftype -> string
5605 * Identifies the type of <i>stat</i>. The return string is one of:
5606 * ``<code>file</code>'', ``<code>directory</code>'',
5607 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5608 * ``<code>fifo</code>'', ``<code>link</code>'',
5609 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5611 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5616 rb_stat_ftype(VALUE obj
)
5618 return rb_file_ftype(get_stat(obj
));
5623 * stat.directory? -> true or false
5625 * Returns <code>true</code> if <i>stat</i> is a directory,
5626 * <code>false</code> otherwise.
5628 * File.stat("testfile").directory? #=> false
5629 * File.stat(".").directory? #=> true
5633 rb_stat_d(VALUE obj
)
5635 if (S_ISDIR(get_stat(obj
)->st_mode
)) return Qtrue
;
5641 * stat.pipe? -> true or false
5643 * Returns <code>true</code> if the operating system supports pipes and
5644 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5648 rb_stat_p(VALUE obj
)
5651 if (S_ISFIFO(get_stat(obj
)->st_mode
)) return Qtrue
;
5659 * stat.symlink? -> true or false
5661 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5662 * <code>false</code> if it isn't or if the operating system doesn't
5663 * support this feature. As File::stat automatically follows symbolic
5664 * links, #symlink? will always be <code>false</code> for an object
5665 * returned by File::stat.
5667 * File.symlink("testfile", "alink") #=> 0
5668 * File.stat("alink").symlink? #=> false
5669 * File.lstat("alink").symlink? #=> true
5674 rb_stat_l(VALUE obj
)
5677 if (S_ISLNK(get_stat(obj
)->st_mode
)) return Qtrue
;
5684 * stat.socket? -> true or false
5686 * Returns <code>true</code> if <i>stat</i> is a socket,
5687 * <code>false</code> if it isn't or if the operating system doesn't
5688 * support this feature.
5690 * File.stat("testfile").socket? #=> false
5695 rb_stat_S(VALUE obj
)
5698 if (S_ISSOCK(get_stat(obj
)->st_mode
)) return Qtrue
;
5706 * stat.blockdev? -> true or false
5708 * Returns <code>true</code> if the file is a block device,
5709 * <code>false</code> if it isn't or if the operating system doesn't
5710 * support this feature.
5712 * File.stat("testfile").blockdev? #=> false
5713 * File.stat("/dev/hda1").blockdev? #=> true
5718 rb_stat_b(VALUE obj
)
5721 if (S_ISBLK(get_stat(obj
)->st_mode
)) return Qtrue
;
5729 * stat.chardev? -> true or false
5731 * Returns <code>true</code> if the file is a character device,
5732 * <code>false</code> if it isn't or if the operating system doesn't
5733 * support this feature.
5735 * File.stat("/dev/tty").chardev? #=> true
5740 rb_stat_c(VALUE obj
)
5742 if (S_ISCHR(get_stat(obj
)->st_mode
)) return Qtrue
;
5749 * stat.owned? -> true or false
5751 * Returns <code>true</code> if the effective user id of the process is
5752 * the same as the owner of <i>stat</i>.
5754 * File.stat("testfile").owned? #=> true
5755 * File.stat("/etc/passwd").owned? #=> false
5760 rb_stat_owned(VALUE obj
)
5762 if (get_stat(obj
)->st_uid
== geteuid()) return Qtrue
;
5767 rb_stat_rowned(VALUE obj
)
5769 if (get_stat(obj
)->st_uid
== getuid()) return Qtrue
;
5775 * stat.grpowned? -> true or false
5777 * Returns true if the effective group id of the process is the same as
5778 * the group id of <i>stat</i>. On Windows NT, returns <code>false</code>.
5780 * File.stat("testfile").grpowned? #=> true
5781 * File.stat("/etc/passwd").grpowned? #=> false
5786 rb_stat_grpowned(VALUE obj
)
5789 if (rb_group_member(get_stat(obj
)->st_gid
)) return Qtrue
;
5796 * stat.readable? -> true or false
5798 * Returns <code>true</code> if <i>stat</i> is readable by the
5799 * effective user id of this process.
5801 * File.stat("testfile").readable? #=> true
5806 rb_stat_r(VALUE obj
)
5808 struct stat
*st
= get_stat(obj
);
5811 if (geteuid() == 0) return Qtrue
;
5814 if (rb_stat_owned(obj
))
5815 return RBOOL(st
->st_mode
& S_IRUSR
);
5818 if (rb_stat_grpowned(obj
))
5819 return RBOOL(st
->st_mode
& S_IRGRP
);
5822 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
5829 * stat.readable_real? -> true or false
5831 * Returns <code>true</code> if <i>stat</i> is readable by the real
5832 * user id of this process.
5834 * File.stat("testfile").readable_real? #=> true
5839 rb_stat_R(VALUE obj
)
5841 struct stat
*st
= get_stat(obj
);
5844 if (getuid() == 0) return Qtrue
;
5847 if (rb_stat_rowned(obj
))
5848 return RBOOL(st
->st_mode
& S_IRUSR
);
5851 if (rb_group_member(get_stat(obj
)->st_gid
))
5852 return RBOOL(st
->st_mode
& S_IRGRP
);
5855 if (!(st
->st_mode
& S_IROTH
)) return Qfalse
;
5862 * stat.world_readable? -> integer or nil
5864 * If <i>stat</i> is readable by others, returns an integer
5865 * representing the file permission bits of <i>stat</i>. Returns
5866 * <code>nil</code> otherwise. The meaning of the bits is platform
5867 * dependent; on Unix systems, see <code>stat(2)</code>.
5869 * m = File.stat("/etc/passwd").world_readable? #=> 420
5870 * sprintf("%o", m) #=> "644"
5874 rb_stat_wr(VALUE obj
)
5877 struct stat
*st
= get_stat(obj
);
5878 if ((st
->st_mode
& (S_IROTH
)) == S_IROTH
) {
5879 return UINT2NUM(st
->st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
5889 * stat.writable? -> true or false
5891 * Returns <code>true</code> if <i>stat</i> is writable by the
5892 * effective user id of this process.
5894 * File.stat("testfile").writable? #=> true
5899 rb_stat_w(VALUE obj
)
5901 struct stat
*st
= get_stat(obj
);
5904 if (geteuid() == 0) return Qtrue
;
5907 if (rb_stat_owned(obj
))
5908 return RBOOL(st
->st_mode
& S_IWUSR
);
5911 if (rb_stat_grpowned(obj
))
5912 return RBOOL(st
->st_mode
& S_IWGRP
);
5915 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
5922 * stat.writable_real? -> true or false
5924 * Returns <code>true</code> if <i>stat</i> is writable by the real
5925 * user id of this process.
5927 * File.stat("testfile").writable_real? #=> true
5932 rb_stat_W(VALUE obj
)
5934 struct stat
*st
= get_stat(obj
);
5937 if (getuid() == 0) return Qtrue
;
5940 if (rb_stat_rowned(obj
))
5941 return RBOOL(st
->st_mode
& S_IWUSR
);
5944 if (rb_group_member(get_stat(obj
)->st_gid
))
5945 return RBOOL(st
->st_mode
& S_IWGRP
);
5948 if (!(st
->st_mode
& S_IWOTH
)) return Qfalse
;
5955 * stat.world_writable? -> integer or nil
5957 * If <i>stat</i> is writable by others, returns an integer
5958 * representing the file permission bits of <i>stat</i>. Returns
5959 * <code>nil</code> otherwise. The meaning of the bits is platform
5960 * dependent; on Unix systems, see <code>stat(2)</code>.
5962 * m = File.stat("/tmp").world_writable? #=> 511
5963 * sprintf("%o", m) #=> "777"
5967 rb_stat_ww(VALUE obj
)
5970 struct stat
*st
= get_stat(obj
);
5971 if ((st
->st_mode
& (S_IWOTH
)) == S_IWOTH
) {
5972 return UINT2NUM(st
->st_mode
& (S_IRUGO
|S_IWUGO
|S_IXUGO
));
5982 * stat.executable? -> true or false
5984 * Returns <code>true</code> if <i>stat</i> is executable or if the
5985 * operating system doesn't distinguish executable files from
5986 * nonexecutable files. The tests are made using the effective owner of
5989 * File.stat("testfile").executable? #=> false
5994 rb_stat_x(VALUE obj
)
5996 struct stat
*st
= get_stat(obj
);
5999 if (geteuid() == 0) {
6000 return RBOOL(st
->st_mode
& S_IXUGO
);
6004 if (rb_stat_owned(obj
))
6005 return RBOOL(st
->st_mode
& S_IXUSR
);
6008 if (rb_stat_grpowned(obj
))
6009 return RBOOL(st
->st_mode
& S_IXGRP
);
6012 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
6019 * stat.executable_real? -> true or false
6021 * Same as <code>executable?</code>, but tests using the real owner of
6026 rb_stat_X(VALUE obj
)
6028 struct stat
*st
= get_stat(obj
);
6031 if (getuid() == 0) {
6032 return RBOOL(st
->st_mode
& S_IXUGO
);
6036 if (rb_stat_rowned(obj
))
6037 return RBOOL(st
->st_mode
& S_IXUSR
);
6040 if (rb_group_member(get_stat(obj
)->st_gid
))
6041 return RBOOL(st
->st_mode
& S_IXGRP
);
6044 if (!(st
->st_mode
& S_IXOTH
)) return Qfalse
;
6051 * stat.file? -> true or false
6053 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6054 * a device file, pipe, socket, etc.).
6056 * File.stat("testfile").file? #=> true
6061 rb_stat_f(VALUE obj
)
6063 if (S_ISREG(get_stat(obj
)->st_mode
)) return Qtrue
;
6069 * stat.zero? -> true or false
6071 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6072 * <code>false</code> otherwise.
6074 * File.stat("testfile").zero? #=> false
6079 rb_stat_z(VALUE obj
)
6081 if (get_stat(obj
)->st_size
== 0) return Qtrue
;
6087 * stat.size? -> Integer or nil
6089 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6090 * the file otherwise.
6092 * File.stat("testfile").size? #=> 66
6093 * File.stat("/dev/null").size? #=> nil
6098 rb_stat_s(VALUE obj
)
6100 off_t size
= get_stat(obj
)->st_size
;
6102 if (size
== 0) return Qnil
;
6103 return OFFT2NUM(size
);
6108 * stat.setuid? -> true or false
6110 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6111 * permission bit set, <code>false</code> if it doesn't or if the
6112 * operating system doesn't support this feature.
6114 * File.stat("/bin/su").setuid? #=> true
6118 rb_stat_suid(VALUE obj
)
6121 if (get_stat(obj
)->st_mode
& S_ISUID
) return Qtrue
;
6128 * stat.setgid? -> true or false
6130 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6131 * permission bit set, <code>false</code> if it doesn't or if the
6132 * operating system doesn't support this feature.
6134 * File.stat("/usr/sbin/lpc").setgid? #=> true
6139 rb_stat_sgid(VALUE obj
)
6142 if (get_stat(obj
)->st_mode
& S_ISGID
) return Qtrue
;
6149 * stat.sticky? -> true or false
6151 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6152 * <code>false</code> if it doesn't or if the operating system doesn't
6153 * support this feature.
6155 * File.stat("testfile").sticky? #=> false
6160 rb_stat_sticky(VALUE obj
)
6163 if (get_stat(obj
)->st_mode
& S_ISVTX
) return Qtrue
;
6168 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6169 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6180 nogvl_mkfifo(void *ptr
)
6182 struct mkfifo_arg
*ma
= ptr
;
6184 return (void *)(VALUE
)mkfifo(ma
->path
, ma
->mode
);
6189 * File.mkfifo(file_name, mode=0666) => 0
6191 * Creates a FIFO special file with name _file_name_. _mode_
6192 * specifies the FIFO's permissions. It is modified by the process's
6193 * umask in the usual way: the permissions of the created file are
6198 rb_file_s_mkfifo(int argc
, VALUE
*argv
, VALUE _
)
6201 struct mkfifo_arg ma
;
6204 rb_check_arity(argc
, 1, 2);
6206 ma
.mode
= NUM2MODET(argv
[1]);
6209 FilePathValue(path
);
6210 path
= rb_str_encode_ospath(path
);
6211 ma
.path
= RSTRING_PTR(path
);
6212 if (rb_thread_call_without_gvl(nogvl_mkfifo
, &ma
, RUBY_UBF_IO
, 0)) {
6213 rb_sys_fail_path(path
);
6218 #define rb_file_s_mkfifo rb_f_notimplement
6221 static VALUE rb_mFConst
;
6224 rb_file_const(const char *name
, VALUE value
)
6226 rb_define_const(rb_mFConst
, name
, value
);
6230 rb_is_absolute_path(const char *path
)
6232 #ifdef DOSISH_DRIVE_LETTER
6233 if (has_drive_letter(path
) && isdirsep(path
[2])) return 1;
6236 if (isdirsep(path
[0]) && isdirsep(path
[1])) return 1;
6239 if (path
[0] == '/') return 1;
6244 #ifndef ENABLE_PATH_CHECK
6245 # if defined DOSISH || defined __CYGWIN__
6246 # define ENABLE_PATH_CHECK 0
6248 # define ENABLE_PATH_CHECK 1
6252 #if ENABLE_PATH_CHECK
6254 path_check_0(VALUE path
)
6257 const char *p0
= StringValueCStr(path
);
6262 if (!rb_is_absolute_path(p0
)) {
6263 char *buf
= ruby_getcwd();
6266 newpath
= rb_str_new2(buf
);
6269 rb_str_cat2(newpath
, "/");
6270 rb_str_cat2(newpath
, p0
);
6272 p0
= RSTRING_PTR(path
);
6274 e0
= p0
+ RSTRING_LEN(path
);
6275 enc
= rb_enc_get(path
);
6278 # define S_IWOTH 002
6280 if (STAT(p0
, &st
) == 0 && S_ISDIR(st
.st_mode
) && (st
.st_mode
& S_IWOTH
)
6282 && !(p
&& (st
.st_mode
& S_ISVTX
))
6284 && !access(p0
, W_OK
)) {
6285 rb_enc_warn(enc
, "Insecure world writable dir %s in PATH, mode 0%"
6286 #if SIZEOF_DEV_T > SIZEOF_INT
6287 PRI_MODET_PREFIX
"o",
6296 s
= strrdirsep(p0
, e0
, enc
);
6298 if (!s
|| s
== p0
) return 1;
6307 rb_path_check(const char *path
)
6309 #if ENABLE_PATH_CHECK
6310 const char *p0
, *p
, *pend
;
6311 const char sep
= PATH_SEP_CHAR
;
6313 if (!path
) return 1;
6315 pend
= path
+ strlen(path
);
6317 p
= strchr(path
, sep
);
6321 if (!path_check_0(rb_str_new(p0
, p
- p0
))) {
6322 return 0; /* not safe */
6325 if (p0
> pend
) break;
6326 p
= strchr(p0
, sep
);
6334 ruby_is_fd_loadable(int fd
)
6341 if (fstat(fd
, &st
) < 0)
6344 if (S_ISREG(st
.st_mode
))
6347 if (S_ISFIFO(st
.st_mode
) || S_ISCHR(st
.st_mode
))
6350 if (S_ISDIR(st
.st_mode
))
6361 rb_file_load_ok(const char *path
)
6365 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6366 FIXME: Why O_NDELAY is checked?
6368 int mode
= (O_RDONLY
|
6369 #if defined O_NONBLOCK
6371 #elif defined O_NDELAY
6375 int fd
= rb_cloexec_open(path
, mode
, 0);
6376 if (fd
== -1) return 0;
6377 rb_update_max_fd(fd
);
6378 ret
= ruby_is_fd_loadable(fd
);
6385 is_explicit_relative(const char *path
)
6387 if (*path
++ != '.') return 0;
6388 if (*path
== '.') path
++;
6389 return isdirsep(*path
);
6393 copy_path_class(VALUE path
, VALUE orig
)
6395 int encidx
= rb_enc_get_index(orig
);
6396 if (encidx
== ENCINDEX_ASCII
|| encidx
== ENCINDEX_US_ASCII
)
6397 encidx
= rb_filesystem_encindex();
6398 rb_enc_associate_index(path
, encidx
);
6400 RBASIC_SET_CLASS(path
, rb_obj_class(orig
));
6406 rb_find_file_ext(VALUE
*filep
, const char *const *ext
)
6408 const char *f
= StringValueCStr(*filep
);
6409 VALUE fname
= *filep
, load_path
, tmp
;
6413 if (!ext
[0]) return 0;
6416 fname
= file_expand_path_1(fname
);
6417 f
= RSTRING_PTR(fname
);
6422 if (expanded
|| rb_is_absolute_path(f
) || is_explicit_relative(f
)) {
6423 if (!expanded
) fname
= file_expand_path_1(fname
);
6424 fnlen
= RSTRING_LEN(fname
);
6425 for (i
=0; ext
[i
]; i
++) {
6426 rb_str_cat2(fname
, ext
[i
]);
6427 if (rb_file_load_ok(RSTRING_PTR(fname
))) {
6428 *filep
= copy_path_class(fname
, *filep
);
6431 rb_str_set_len(fname
, fnlen
);
6436 RB_GC_GUARD(load_path
) = rb_get_expanded_load_path();
6437 if (!load_path
) return 0;
6439 fname
= rb_str_dup(*filep
);
6440 RBASIC_CLEAR_CLASS(fname
);
6441 fnlen
= RSTRING_LEN(fname
);
6442 tmp
= rb_str_tmp_new(MAXPATHLEN
+ 2);
6443 rb_enc_associate_index(tmp
, rb_usascii_encindex());
6444 for (j
=0; ext
[j
]; j
++) {
6445 rb_str_cat2(fname
, ext
[j
]);
6446 for (i
= 0; i
< RARRAY_LEN(load_path
); i
++) {
6447 VALUE str
= RARRAY_AREF(load_path
, i
);
6449 RB_GC_GUARD(str
) = rb_get_path(str
);
6450 if (RSTRING_LEN(str
) == 0) continue;
6451 rb_file_expand_path_internal(fname
, str
, 0, 0, tmp
);
6452 if (rb_file_load_ok(RSTRING_PTR(tmp
))) {
6453 *filep
= copy_path_class(tmp
, *filep
);
6457 rb_str_set_len(fname
, fnlen
);
6459 rb_str_resize(tmp
, 0);
6460 RB_GC_GUARD(load_path
);
6465 rb_find_file(VALUE path
)
6467 VALUE tmp
, load_path
;
6468 const char *f
= StringValueCStr(path
);
6472 tmp
= file_expand_path_1(path
);
6473 path
= copy_path_class(tmp
, path
);
6474 f
= RSTRING_PTR(path
);
6478 if (expanded
|| rb_is_absolute_path(f
) || is_explicit_relative(f
)) {
6479 if (!rb_file_load_ok(f
)) return 0;
6481 path
= copy_path_class(file_expand_path_1(path
), path
);
6485 RB_GC_GUARD(load_path
) = rb_get_expanded_load_path();
6489 tmp
= rb_str_tmp_new(MAXPATHLEN
+ 2);
6490 rb_enc_associate_index(tmp
, rb_usascii_encindex());
6491 for (i
= 0; i
< RARRAY_LEN(load_path
); i
++) {
6492 VALUE str
= RARRAY_AREF(load_path
, i
);
6493 RB_GC_GUARD(str
) = rb_get_path(str
);
6494 if (RSTRING_LEN(str
) > 0) {
6495 rb_file_expand_path_internal(path
, str
, 0, 0, tmp
);
6496 f
= RSTRING_PTR(tmp
);
6497 if (rb_file_load_ok(f
)) goto found
;
6500 rb_str_resize(tmp
, 0);
6504 return 0; /* no path, no load */
6508 return copy_path_class(tmp
, path
);
6512 define_filetest_function(const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
6514 rb_define_module_function(rb_mFileTest
, name
, func
, argc
);
6515 rb_define_singleton_method(rb_cFile
, name
, func
, argc
);
6518 const char ruby_null_device
[] =
6521 #elif defined AMIGA || defined __amigaos__
6531 * A File is an abstraction of any file object accessible by the
6532 * program and is closely associated with class IO. File includes
6533 * the methods of module FileTest as class methods, allowing you to
6534 * write (for example) <code>File.exist?("foo")</code>.
6536 * In the description of File methods,
6537 * <em>permission bits</em> are a platform-specific
6538 * set of bits that indicate permissions of a file. On Unix-based
6539 * systems, permissions are viewed as a set of three octets, for the
6540 * owner, the group, and the rest of the world. For each of these
6541 * entities, permissions may be set to read, write, or execute the
6544 * The permission bits <code>0644</code> (in octal) would thus be
6545 * interpreted as read/write for owner, and read-only for group and
6546 * other. Higher-order bits may also be used to indicate the type of
6547 * file (plain, directory, pipe, socket, and so on) and various other
6548 * special features. If the permissions are for a directory, the
6549 * meaning of the execute bit changes; when set the directory can be
6552 * On non-Posix operating systems, there may be only the ability to
6553 * make a file read-only or read-write. In this case, the remaining
6554 * permission bits will be synthesized to resemble typical values. For
6555 * instance, on Windows NT the default permission bits are
6556 * <code>0644</code>, which means read/write for owner, read-only for
6557 * all others. The only change that can be made is to make the file
6558 * read-only, which is reported as <code>0444</code>.
6560 * Various constants for the methods in File can be found in File::Constants.
6564 * First, what's elsewhere. \Class \File:
6566 * - Inherits from {class IO}[IO.html#class-IO-label-What-27s+Here],
6567 * in particular, methods for creating, reading, and writing files
6568 * - Includes {module FileTest}[FileTest.html#module-FileTest-label-What-27s+Here].
6569 * which provides dozens of additional methods.
6571 * Here, class \File provides methods that are useful for:
6573 * - {Creating}[#class-File-label-Creating]
6574 * - {Querying}[#class-File-label-Querying]
6575 * - {Settings}[#class-File-label-Settings]
6576 * - {Other}[#class-File-label-Other]
6580 * - ::new:: Opens the file at the given path; returns the file.
6581 * - ::open:: Same as ::new, but when given a block will yield the file to the block,
6582 * and close the file upon exiting the block.
6583 * - ::link:: Creates a new name for an existing file using a hard link.
6584 * - ::mkfifo:: Returns the FIFO file created at the given path.
6585 * - ::symlink:: Creates a symbolic link for the given file path.
6591 * - ::absolute_path:: Returns the absolute file path for the given path.
6592 * - ::absolute_path?:: Returns whether the given path is the absolute file path.
6593 * - ::basename:: Returns the last component of the given file path.
6594 * - ::dirname:: Returns all but the last component of the given file path.
6595 * - ::expand_path:: Returns the absolute file path for the given path,
6596 * expanding <tt>~</tt> for a home directory.
6597 * - ::extname:: Returns the file extension for the given file path.
6598 * - ::fnmatch? (aliased as ::fnmatch):: Returns whether the given file path
6599 * matches the given pattern.
6600 * - ::join:: Joins path components into a single path string.
6601 * - ::path:: Returns the string representation of the given path.
6602 * - ::readlink:: Returns the path to the file at the given symbolic link.
6603 * - ::realdirpath:: Returns the real path for the given file path,
6604 * where the last component need not exist.
6605 * - ::realpath:: Returns the real path for the given file path,
6606 * where all components must exist.
6607 * - ::split:: Returns an array of two strings: the directory name and basename
6608 * of the file at the given path.
6609 * - #path (aliased as #to_path):: Returns the string representation of the given path.
6613 * - ::atime:: Returns a \Time for the most recent access to the given file.
6614 * - ::birthtime:: Returns a \Time for the creation of the given file.
6615 * - ::ctime:: Returns a \Time for the metadata change of the given file.
6616 * - ::mtime:: Returns a \Time for the most recent data modification to
6617 * the content of the given file.
6618 * - #atime:: Returns a \Time for the most recent access to +self+.
6619 * - #birthtime:: Returns a \Time the creation for +self+.
6620 * - #ctime:: Returns a \Time for the metadata change of +self+.
6621 * - #mtime:: Returns a \Time for the most recent data modification
6622 * to the content of +self+.
6626 * - ::blockdev?:: Returns whether the file at the given path is a block device.
6627 * - ::chardev?:: Returns whether the file at the given path is a character device.
6628 * - ::directory?:: Returns whether the file at the given path is a diretory.
6629 * - ::executable?:: Returns whether the file at the given path is executable
6630 * by the effective user and group of the current process.
6631 * - ::executable_real?:: Returns whether the file at the given path is executable
6632 * by the real user and group of the current process.
6633 * - ::exist?:: Returns whether the file at the given path exists.
6634 * - ::file?:: Returns whether the file at the given path is a regular file.
6635 * - ::ftype:: Returns a string giving the type of the file at the given path.
6636 * - ::grpowned?:: Returns whether the effective group of the current process
6637 * owns the file at the given path.
6638 * - ::identical?:: Returns whether the files at two given paths are identical.
6639 * - ::lstat:: Returns the File::Stat object for the last symbolic link
6640 * in the given path.
6641 * - ::owned?:: Returns whether the effective user of the current process
6642 * owns the file at the given path.
6643 * - ::pipe?:: Returns whether the file at the given path is a pipe.
6644 * - ::readable?:: Returns whether the file at the given path is readable
6645 * by the effective user and group of the current process.
6646 * - ::readable_real?:: Returns whether the file at the given path is readable
6647 * by the real user and group of the current process.
6648 * - ::setgid?:: Returns whether the setgid bit is set for the file at the given path.
6649 * - ::setuid?:: Returns whether the setuid bit is set for the file at the given path.
6650 * - ::socket?:: Returns whether the file at the given path is a socket.
6651 * - ::stat:: Returns the File::Stat object for the file at the given path.
6652 * - ::sticky?:: Returns whether the file at the given path has its sticky bit set.
6653 * - ::symlink?:: Returns whether the file at the given path is a symbolic link.
6654 * - ::umask:: Returns the umask value for the current process.
6655 * - ::world_readable?:: Returns whether the file at the given path is readable
6657 * - ::world_writable?:: Returns whether the file at the given path is writable
6659 * - ::writable?:: Returns whether the file at the given path is writable
6660 * by the effective user and group of the current process.
6661 * - ::writable_real?:: Returns whether the file at the given path is writable
6662 * by the real user and group of the current process.
6663 * - #lstat:: Returns the File::Stat object for the last symbolic link
6664 * in the path for +self+.
6668 * - ::empty? (aliased as ::zero?):: Returns whether the file at the given path
6669 * exists and is empty.
6670 * - ::size:: Returns the size (bytes) of the file at the given path.
6671 * - ::size?:: Returns +nil+ if there is no file at the given path,
6672 * or if that file is empty; otherwise returns the file size (bytes).
6673 * - #size:: Returns the size (bytes) of +self+.
6677 * - ::chmod:: Changes permissions of the file at the given path.
6678 * - ::chown:: Change ownership of the file at the given path.
6679 * - ::lchmod:: Changes permissions of the last symbolic link in the given path.
6680 * - ::lchown:: Change ownership of the last symbolic in the given path.
6681 * - ::lutime:: For each given file path, sets the access time and modification time
6682 * of the last symbolic link in the path.
6683 * - ::rename:: Moves the file at one given path to another given path.
6684 * - ::utime:: Sets the access time and modification time of each file
6685 * at the given paths.
6686 * - #flock:: Locks or unlocks +self+.
6690 * - ::truncate:: Truncates the file at the given file path to the given size.
6691 * - ::unlink (aliased as ::delete):: Deletes the file for each given file path.
6692 * - #truncate:: Truncates +self+ to the given size.
6701 rb_mFileTest
= rb_define_module("FileTest");
6702 rb_cFile
= rb_define_class("File", rb_cIO
);
6704 define_filetest_function("directory?", rb_file_directory_p
, 1);
6705 define_filetest_function("exist?", rb_file_exist_p
, 1);
6706 define_filetest_function("exists?", rb_file_exists_p
, 1);
6707 define_filetest_function("readable?", rb_file_readable_p
, 1);
6708 define_filetest_function("readable_real?", rb_file_readable_real_p
, 1);
6709 define_filetest_function("world_readable?", rb_file_world_readable_p
, 1);
6710 define_filetest_function("writable?", rb_file_writable_p
, 1);
6711 define_filetest_function("writable_real?", rb_file_writable_real_p
, 1);
6712 define_filetest_function("world_writable?", rb_file_world_writable_p
, 1);
6713 define_filetest_function("executable?", rb_file_executable_p
, 1);
6714 define_filetest_function("executable_real?", rb_file_executable_real_p
, 1);
6715 define_filetest_function("file?", rb_file_file_p
, 1);
6716 define_filetest_function("zero?", rb_file_zero_p
, 1);
6717 define_filetest_function("empty?", rb_file_zero_p
, 1);
6718 define_filetest_function("size?", rb_file_size_p
, 1);
6719 define_filetest_function("size", rb_file_s_size
, 1);
6720 define_filetest_function("owned?", rb_file_owned_p
, 1);
6721 define_filetest_function("grpowned?", rb_file_grpowned_p
, 1);
6723 define_filetest_function("pipe?", rb_file_pipe_p
, 1);
6724 define_filetest_function("symlink?", rb_file_symlink_p
, 1);
6725 define_filetest_function("socket?", rb_file_socket_p
, 1);
6727 define_filetest_function("blockdev?", rb_file_blockdev_p
, 1);
6728 define_filetest_function("chardev?", rb_file_chardev_p
, 1);
6730 define_filetest_function("setuid?", rb_file_suid_p
, 1);
6731 define_filetest_function("setgid?", rb_file_sgid_p
, 1);
6732 define_filetest_function("sticky?", rb_file_sticky_p
, 1);
6734 define_filetest_function("identical?", rb_file_identical_p
, 2);
6736 rb_define_singleton_method(rb_cFile
, "stat", rb_file_s_stat
, 1);
6737 rb_define_singleton_method(rb_cFile
, "lstat", rb_file_s_lstat
, 1);
6738 rb_define_singleton_method(rb_cFile
, "ftype", rb_file_s_ftype
, 1);
6740 rb_define_singleton_method(rb_cFile
, "atime", rb_file_s_atime
, 1);
6741 rb_define_singleton_method(rb_cFile
, "mtime", rb_file_s_mtime
, 1);
6742 rb_define_singleton_method(rb_cFile
, "ctime", rb_file_s_ctime
, 1);
6743 rb_define_singleton_method(rb_cFile
, "birthtime", rb_file_s_birthtime
, 1);
6745 rb_define_singleton_method(rb_cFile
, "utime", rb_file_s_utime
, -1);
6746 rb_define_singleton_method(rb_cFile
, "chmod", rb_file_s_chmod
, -1);
6747 rb_define_singleton_method(rb_cFile
, "chown", rb_file_s_chown
, -1);
6748 rb_define_singleton_method(rb_cFile
, "lchmod", rb_file_s_lchmod
, -1);
6749 rb_define_singleton_method(rb_cFile
, "lchown", rb_file_s_lchown
, -1);
6750 rb_define_singleton_method(rb_cFile
, "lutime", rb_file_s_lutime
, -1);
6752 rb_define_singleton_method(rb_cFile
, "link", rb_file_s_link
, 2);
6753 rb_define_singleton_method(rb_cFile
, "symlink", rb_file_s_symlink
, 2);
6754 rb_define_singleton_method(rb_cFile
, "readlink", rb_file_s_readlink
, 1);
6756 rb_define_singleton_method(rb_cFile
, "unlink", rb_file_s_unlink
, -1);
6757 rb_define_singleton_method(rb_cFile
, "delete", rb_file_s_unlink
, -1);
6758 rb_define_singleton_method(rb_cFile
, "rename", rb_file_s_rename
, 2);
6759 rb_define_singleton_method(rb_cFile
, "umask", rb_file_s_umask
, -1);
6760 rb_define_singleton_method(rb_cFile
, "truncate", rb_file_s_truncate
, 2);
6761 rb_define_singleton_method(rb_cFile
, "mkfifo", rb_file_s_mkfifo
, -1);
6762 rb_define_singleton_method(rb_cFile
, "expand_path", s_expand_path
, -1);
6763 rb_define_singleton_method(rb_cFile
, "absolute_path", s_absolute_path
, -1);
6764 rb_define_singleton_method(rb_cFile
, "absolute_path?", s_absolute_path_p
, 1);
6765 rb_define_singleton_method(rb_cFile
, "realpath", rb_file_s_realpath
, -1);
6766 rb_define_singleton_method(rb_cFile
, "realdirpath", rb_file_s_realdirpath
, -1);
6767 rb_define_singleton_method(rb_cFile
, "basename", rb_file_s_basename
, -1);
6768 rb_define_singleton_method(rb_cFile
, "dirname", rb_file_s_dirname
, -1);
6769 rb_define_singleton_method(rb_cFile
, "extname", rb_file_s_extname
, 1);
6770 rb_define_singleton_method(rb_cFile
, "path", rb_file_s_path
, 1);
6772 separator
= rb_fstring_lit("/");
6773 /* separates directory parts in path */
6774 rb_define_const(rb_cFile
, "Separator", separator
);
6775 /* separates directory parts in path */
6776 rb_define_const(rb_cFile
, "SEPARATOR", separator
);
6777 rb_define_singleton_method(rb_cFile
, "split", rb_file_s_split
, 1);
6778 rb_define_singleton_method(rb_cFile
, "join", rb_file_s_join
, -2);
6781 /* platform specific alternative separator */
6782 rb_define_const(rb_cFile
, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator
)));
6784 rb_define_const(rb_cFile
, "ALT_SEPARATOR", Qnil
);
6786 /* path list separator */
6787 rb_define_const(rb_cFile
, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP
));
6789 rb_define_method(rb_cIO
, "stat", rb_io_stat
, 0); /* this is IO's method */
6790 rb_define_method(rb_cFile
, "lstat", rb_file_lstat
, 0);
6792 rb_define_method(rb_cFile
, "atime", rb_file_atime
, 0);
6793 rb_define_method(rb_cFile
, "mtime", rb_file_mtime
, 0);
6794 rb_define_method(rb_cFile
, "ctime", rb_file_ctime
, 0);
6795 rb_define_method(rb_cFile
, "birthtime", rb_file_birthtime
, 0);
6796 rb_define_method(rb_cFile
, "size", file_size
, 0);
6798 rb_define_method(rb_cFile
, "chmod", rb_file_chmod
, 1);
6799 rb_define_method(rb_cFile
, "chown", rb_file_chown
, 2);
6800 rb_define_method(rb_cFile
, "truncate", rb_file_truncate
, 1);
6802 rb_define_method(rb_cFile
, "flock", rb_file_flock
, 1);
6805 * Document-module: File::Constants
6807 * File::Constants provides file-related constants. All possible
6808 * file constants are listed in the documentation but they may not all
6809 * be present on your platform.
6811 * If the underlying platform doesn't define a constant the corresponding
6812 * Ruby constant is not defined.
6814 * Your platform documentations (e.g. man open(2)) may describe more
6815 * detailed information.
6817 rb_mFConst
= rb_define_module_under(rb_cFile
, "Constants");
6818 rb_include_module(rb_cIO
, rb_mFConst
);
6820 /* open for reading only */
6821 rb_define_const(rb_mFConst
, "RDONLY", INT2FIX(O_RDONLY
));
6822 /* open for writing only */
6823 rb_define_const(rb_mFConst
, "WRONLY", INT2FIX(O_WRONLY
));
6824 /* open for reading and writing */
6825 rb_define_const(rb_mFConst
, "RDWR", INT2FIX(O_RDWR
));
6826 /* append on each write */
6827 rb_define_const(rb_mFConst
, "APPEND", INT2FIX(O_APPEND
));
6828 /* create file if it does not exist */
6829 rb_define_const(rb_mFConst
, "CREAT", INT2FIX(O_CREAT
));
6830 /* error if CREAT and the file exists */
6831 rb_define_const(rb_mFConst
, "EXCL", INT2FIX(O_EXCL
));
6832 #if defined(O_NDELAY) || defined(O_NONBLOCK)
6834 # define O_NONBLOCK O_NDELAY
6836 /* do not block on open or for data to become available */
6837 rb_define_const(rb_mFConst
, "NONBLOCK", INT2FIX(O_NONBLOCK
));
6839 /* truncate size to 0 */
6840 rb_define_const(rb_mFConst
, "TRUNC", INT2FIX(O_TRUNC
));
6842 /* not to make opened IO the controlling terminal device */
6843 rb_define_const(rb_mFConst
, "NOCTTY", INT2FIX(O_NOCTTY
));
6848 /* disable line code conversion */
6849 rb_define_const(rb_mFConst
, "BINARY", INT2FIX(O_BINARY
));
6850 #ifndef O_SHARE_DELETE
6851 # define O_SHARE_DELETE 0
6853 /* can delete opened file */
6854 rb_define_const(rb_mFConst
, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE
));
6856 /* any write operation perform synchronously */
6857 rb_define_const(rb_mFConst
, "SYNC", INT2FIX(O_SYNC
));
6860 /* any write operation perform synchronously except some meta data */
6861 rb_define_const(rb_mFConst
, "DSYNC", INT2FIX(O_DSYNC
));
6864 /* any read operation perform synchronously. used with SYNC or DSYNC. */
6865 rb_define_const(rb_mFConst
, "RSYNC", INT2FIX(O_RSYNC
));
6868 /* do not follow symlinks */
6869 rb_define_const(rb_mFConst
, "NOFOLLOW", INT2FIX(O_NOFOLLOW
)); /* FreeBSD, Linux */
6872 /* do not change atime */
6873 rb_define_const(rb_mFConst
, "NOATIME", INT2FIX(O_NOATIME
)); /* Linux */
6876 /* Try to minimize cache effects of the I/O to and from this file. */
6877 rb_define_const(rb_mFConst
, "DIRECT", INT2FIX(O_DIRECT
));
6880 /* Create an unnamed temporary file */
6881 rb_define_const(rb_mFConst
, "TMPFILE", INT2FIX(O_TMPFILE
));
6884 /* shared lock. see File#flock */
6885 rb_define_const(rb_mFConst
, "LOCK_SH", INT2FIX(LOCK_SH
));
6886 /* exclusive lock. see File#flock */
6887 rb_define_const(rb_mFConst
, "LOCK_EX", INT2FIX(LOCK_EX
));
6888 /* unlock. see File#flock */
6889 rb_define_const(rb_mFConst
, "LOCK_UN", INT2FIX(LOCK_UN
));
6890 /* non-blocking lock. used with LOCK_SH or LOCK_EX. see File#flock */
6891 rb_define_const(rb_mFConst
, "LOCK_NB", INT2FIX(LOCK_NB
));
6893 /* Name of the null device */
6894 rb_define_const(rb_mFConst
, "NULL", rb_fstring_cstr(ruby_null_device
));
6896 rb_define_method(rb_cFile
, "path", rb_file_path
, 0);
6897 rb_define_method(rb_cFile
, "to_path", rb_file_path
, 0);
6898 rb_define_global_function("test", rb_f_test
, -1);
6900 rb_cStat
= rb_define_class_under(rb_cFile
, "Stat", rb_cObject
);
6901 rb_define_alloc_func(rb_cStat
, rb_stat_s_alloc
);
6902 rb_define_method(rb_cStat
, "initialize", rb_stat_init
, 1);
6903 rb_define_method(rb_cStat
, "initialize_copy", rb_stat_init_copy
, 1);
6905 rb_include_module(rb_cStat
, rb_mComparable
);
6907 rb_define_method(rb_cStat
, "<=>", rb_stat_cmp
, 1);
6909 rb_define_method(rb_cStat
, "dev", rb_stat_dev
, 0);
6910 rb_define_method(rb_cStat
, "dev_major", rb_stat_dev_major
, 0);
6911 rb_define_method(rb_cStat
, "dev_minor", rb_stat_dev_minor
, 0);
6912 rb_define_method(rb_cStat
, "ino", rb_stat_ino
, 0);
6913 rb_define_method(rb_cStat
, "mode", rb_stat_mode
, 0);
6914 rb_define_method(rb_cStat
, "nlink", rb_stat_nlink
, 0);
6915 rb_define_method(rb_cStat
, "uid", rb_stat_uid
, 0);
6916 rb_define_method(rb_cStat
, "gid", rb_stat_gid
, 0);
6917 rb_define_method(rb_cStat
, "rdev", rb_stat_rdev
, 0);
6918 rb_define_method(rb_cStat
, "rdev_major", rb_stat_rdev_major
, 0);
6919 rb_define_method(rb_cStat
, "rdev_minor", rb_stat_rdev_minor
, 0);
6920 rb_define_method(rb_cStat
, "size", rb_stat_size
, 0);
6921 rb_define_method(rb_cStat
, "blksize", rb_stat_blksize
, 0);
6922 rb_define_method(rb_cStat
, "blocks", rb_stat_blocks
, 0);
6923 rb_define_method(rb_cStat
, "atime", rb_stat_atime
, 0);
6924 rb_define_method(rb_cStat
, "mtime", rb_stat_mtime
, 0);
6925 rb_define_method(rb_cStat
, "ctime", rb_stat_ctime
, 0);
6926 rb_define_method(rb_cStat
, "birthtime", rb_stat_birthtime
, 0);
6928 rb_define_method(rb_cStat
, "inspect", rb_stat_inspect
, 0);
6930 rb_define_method(rb_cStat
, "ftype", rb_stat_ftype
, 0);
6932 rb_define_method(rb_cStat
, "directory?", rb_stat_d
, 0);
6933 rb_define_method(rb_cStat
, "readable?", rb_stat_r
, 0);
6934 rb_define_method(rb_cStat
, "readable_real?", rb_stat_R
, 0);
6935 rb_define_method(rb_cStat
, "world_readable?", rb_stat_wr
, 0);
6936 rb_define_method(rb_cStat
, "writable?", rb_stat_w
, 0);
6937 rb_define_method(rb_cStat
, "writable_real?", rb_stat_W
, 0);
6938 rb_define_method(rb_cStat
, "world_writable?", rb_stat_ww
, 0);
6939 rb_define_method(rb_cStat
, "executable?", rb_stat_x
, 0);
6940 rb_define_method(rb_cStat
, "executable_real?", rb_stat_X
, 0);
6941 rb_define_method(rb_cStat
, "file?", rb_stat_f
, 0);
6942 rb_define_method(rb_cStat
, "zero?", rb_stat_z
, 0);
6943 rb_define_method(rb_cStat
, "size?", rb_stat_s
, 0);
6944 rb_define_method(rb_cStat
, "owned?", rb_stat_owned
, 0);
6945 rb_define_method(rb_cStat
, "grpowned?", rb_stat_grpowned
, 0);
6947 rb_define_method(rb_cStat
, "pipe?", rb_stat_p
, 0);
6948 rb_define_method(rb_cStat
, "symlink?", rb_stat_l
, 0);
6949 rb_define_method(rb_cStat
, "socket?", rb_stat_S
, 0);
6951 rb_define_method(rb_cStat
, "blockdev?", rb_stat_b
, 0);
6952 rb_define_method(rb_cStat
, "chardev?", rb_stat_c
, 0);
6954 rb_define_method(rb_cStat
, "setuid?", rb_stat_suid
, 0);
6955 rb_define_method(rb_cStat
, "setgid?", rb_stat_sgid
, 0);
6956 rb_define_method(rb_cStat
, "sticky?", rb_stat_sticky
, 0);