AFile is an abstraction of any file objectaccessible by the program and is closely associated with classIO.File includes the methodsof moduleFileTest as class methods, allowingyou to write (for example)File.exist?("foo")
.
In the description ofFile methods,permissionbits are a platform-specific set of bits that indicate permissions ofa file. On Unix-based systems, permissions are viewed as a set of threeoctets, for the owner, the group, and the rest of the world. For each ofthese entities, permissions may be set to read, write, or execute the file:
The permission bits0644
(in octal) would thus be interpretedas read/write for owner, and read-only for group and other. Higher-orderbits may also be used to indicate the type of file (plain, directory, pipe,socket, and so on) and various other special features. If the permissionsare for a directory, the meaning of the execute bit changes; when set thedirectory can be searched.
On non-Posix operating systems, there may be only the ability to make afile read-only or read-write. In this case, the remaining permission bitswill be synthesized to resemble typical values. For instance, on Windows NTthe default permission bits are0644
, which means read/writefor owner, read-only for all others. The only change that can be made is tomake the file read-only, which is reported as0444
.
Various constants for the methods inFile can befound inFile::Constants.
platform specific alternative separator
path list separator
separates directory parts in path
separates directory parts in path
Converts a pathname to an absolute pathname. Relative paths are referencedfrom the current working directory of the process unlessdir_string is given, in which case it will be used as the startingpoint. If the given pathname starts with a “~
'' it isNOT expanded, it is treated as a normal directory name.
File.absolute_path("~oracle/bin")#=> "<relative_path>/~oracle/bin"
static VALUEs_absolute_path(int c, const VALUE * v, VALUE _){ return rb_file_s_absolute_path(c, v);}
Returnstrue
iffile_name
is an absolute path,andfalse
otherwise.
File.absolute_path?("c:/foo")#=> false (on Linux), true (on Windows)
static VALUEs_absolute_path_p(VALUE klass, VALUE fname){ VALUE path = rb_get_path(fname); if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse; return Qtrue;}
Returns the last access time for the named file as aTime object.
file_name can be anIO object.
File.atime("testfile")#=> Wed Apr 09 08:51:48 CDT 2003
static VALUErb_file_s_atime(VALUE klass, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_atime(&st);}
Returns the last component of the filename given infile_name(after first stripping trailing separators), which can be formed using bothFile::SEPARATOR andFile::ALT_SEPARATOR as the separatorwhenFile::ALT_SEPARATOR is notnil
. Ifsuffix is given and present at the end offile_name, it is removed. Ifsuffix is “.*”, anyextension will be removed.
File.basename("/home/gumby/work/ruby.rb")#=> "ruby.rb"File.basename("/home/gumby/work/ruby.rb",".rb")#=> "ruby"File.basename("/home/gumby/work/ruby.rb",".*")#=> "ruby"
static VALUErb_file_s_basename(int argc, VALUE *argv, VALUE _){ VALUE fname, fext, basename; const char *name, *p; long f, n; rb_encoding *enc; fext = Qnil; if (rb_check_arity(argc, 1, 2) == 2) { fext = argv[1]; StringValue(fext); enc = check_path_encoding(fext); } fname = argv[0]; FilePathStringValue(fname); if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) { enc = rb_enc_get(fname); fext = Qnil; } if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname))) return rb_str_new_shared(fname); p = ruby_enc_find_basename(name, &f, &n, enc); if (n >= 0) { if (NIL_P(fext)) { f = n; } else { const char *fp; fp = StringValueCStr(fext); if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) { f = n; } RB_GC_GUARD(fext); } if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname); } basename = rb_str_new(p, f); rb_enc_copy(basename, fname); return basename;}
RUBY_FUNC_EXPORTED VALUErb_file_s_birthtime(VALUE klass, VALUE fname){ statx_data st; if (rb_statx(fname, &st, STATX_BTIME) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return statx_birthtime(&st, fname);}
Returnstrue
if the named file is a block device.
file_name can be anIO object.
static VALUErb_file_blockdev_p(VALUE obj, VALUE fname){#ifndef S_ISBLK# ifdef S_IFBLK# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)# else# define S_ISBLK(m) (0) /* anytime false */# endif#endif#ifdef S_ISBLK struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISBLK(st.st_mode)) return Qtrue;#endif return Qfalse;}
Returnstrue
if the named file is a character device.
file_name can be anIO object.
static VALUErb_file_chardev_p(VALUE obj, VALUE fname){#ifndef S_ISCHR# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)#endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISCHR(st.st_mode)) return Qtrue; return Qfalse;}
Changes permission bits on the named file(s) to the bit pattern representedbymode_int. Actual effects are operating system dependent (seethe beginning of this section). On Unix systems, seechmod(2)
for details. Returns the number of files processed.
File.chmod(0644,"testfile","out")#=> 2
static VALUErb_file_s_chmod(int argc, VALUE *argv, VALUE _){ mode_t mode; apply2args(1); mode = NUM2MODET(*argv++); return apply2files(chmod_internal, argc, argv, &mode);}
Changes the owner and group of the named file(s) to the given numeric ownerand group id's. Only a process with superuser privileges may change theowner of a file. The current owner of a file may change the file'sgroup to any group to which the owner belongs. Anil
or -1owner or group id is ignored. Returns the number of files processed.
File.chown(nil,100,"testfile")
static VALUErb_file_s_chown(int argc, VALUE *argv, VALUE _){ struct chown_args arg; apply2args(2); arg.owner = to_uid(*argv++); arg.group = to_gid(*argv++); return apply2files(chown_internal, argc, argv, &arg);}
Returns the change time for the named file (the time at which directoryinformation about the file was changed, not the file itself).
file_name can be anIO object.
Note that on Windows (NTFS), returns creation time (birth time).
File.ctime("testfile")#=> Wed Apr 09 08:53:13 CDT 2003
static VALUErb_file_s_ctime(VALUE klass, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_ctime(&st);}
Deletes the named files, returning the number of names passed as arguments.Raises an exception on any error. Since the underlying implementationrelies on theunlink(2)
system call, the type of exceptionraised depends on its error type (seelinux.die.net/man/2/unlink)and has the form of e.g. Errno::ENOENT.
See alsoDir.rmdir.
static VALUErb_file_s_unlink(int argc, VALUE *argv, VALUE klass){ return apply2files(unlink_internal, argc, argv, 0);}
Returnstrue
if the named file is a directory, or a symlinkthat points at a directory, andfalse
otherwise.
file_name can be anIO object.
File.directory?(".")
VALUErb_file_directory_p(VALUE obj, VALUE fname){#ifndef S_ISDIR# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)#endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISDIR(st.st_mode)) return Qtrue; return Qfalse;}
Returns all components of the filename given infile_name exceptthe last one (after first stripping trailing separators). The filename canbe formed using bothFile::SEPARATOR andFile::ALT_SEPARATOR as the separatorwhenFile::ALT_SEPARATOR is notnil
.
File.dirname("/home/gumby/work/ruby.rb")#=> "/home/gumby/work"
static VALUErb_file_s_dirname(VALUE klass, VALUE fname){ return rb_file_dirname(fname);}
Returnstrue
if the named file exists and has a zero size.
file_name can be anIO object.
static VALUErb_file_zero_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (st.st_size == 0) return Qtrue; return Qfalse;}
Returnstrue
if the named file is executable by the effectiveuser and group id of this process. See eaccess(3).
Windows does not support execute permissions separately from readpermissions. On Windows, a file is only considered executable if it ends in.bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return trueeven though the file is not executable by the effective user/group.
static VALUErb_file_executable_p(VALUE obj, VALUE fname){ if (rb_eaccess(fname, X_OK) < 0) return Qfalse; return Qtrue;}
Returnstrue
if the named file is executable by the real userand group id of this process. See access(3).
Windows does not support execute permissions separately from readpermissions. On Windows, a file is only considered executable if it ends in.bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return trueeven though the file is not executable by the real user/group.
static VALUErb_file_executable_real_p(VALUE obj, VALUE fname){ if (rb_access(fname, X_OK) < 0) return Qfalse; return Qtrue;}
Returntrue
if the named file exists.
file_name can be anIO object.
“file exists” means that stat() or fstat() system call is successful.
static VALUErb_file_exist_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return Qtrue;}
Converts a pathname to an absolute pathname. Relative paths are referencedfrom the current working directory of the process unlessdir_string
is given, in which case it will be used as thestarting point. The given pathname may start with a“~
'', which expands to the process owner's homedirectory (the environment variableHOME
must be setcorrectly). “~
user'' expands to the nameduser's home directory.
File.expand_path("~oracle/bin")#=> "/home/oracle/bin"
A simple example of usingdir_string
is as follows.
File.expand_path("ruby","/usr/bin")#=> "/usr/bin/ruby"
A more complex example which also resolves parent directory is as follows.Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
File.expand_path("../../lib/mygem.rb",__FILE__)#=> ".../path/to/project/lib/mygem.rb"
So first it resolves the parent of __FILE__, that is bin/, then go to theparent, the root of the project and appendslib/mygem.rb
.
static VALUEs_expand_path(int c, const VALUE * v, VALUE _){ return rb_file_s_expand_path(c, v);}
Returns the extension (the portion of file name inpath
starting from the last period).
Ifpath
is a dotfile, or starts with a period, then thestarting dot is not dealt with the start of the extension.
An empty string will also be returned when the period is the last characterinpath
.
On Windows, trailing dots are truncated.
File.extname("test.rb")#=> ".rb"File.extname("a/b/d/test.rb")#=> ".rb"File.extname(".a/b/d/test.rb")#=> ".rb"File.extname("foo.")#=> "" on WindowsFile.extname("foo.")#=> "." on non-WindowsFile.extname("test")#=> ""File.extname(".profile")#=> ""File.extname(".profile.sh")#=> ".sh"
static VALUErb_file_s_extname(VALUE klass, VALUE fname){ const char *name, *e; long len; VALUE extname; FilePathStringValue(fname); name = StringValueCStr(fname); len = RSTRING_LEN(fname); e = ruby_enc_find_extname(name, &len, rb_enc_get(fname)); if (len < 1) return rb_str_new(0, 0); extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */ return extname;}
Returnstrue
if the namedfile
exists and is aregular file.
file
can be anIO object.
If thefile
argument is a symbolic link, it will resolve thesymbolic link and use the file referenced by the link.
static VALUErb_file_file_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISREG(st.st_mode)) return Qtrue; return Qfalse;}
Returns true ifpath
matches againstpattern
. The pattern is not a regular expression; instead it follows rules similarto shell filename globbing. It may contain the following metacharacters:
*
Matches any file. Can be restricted by other values in the glob. Equivalentto/ .* /x
in regexp.
*
Matches all files regular files
c*
Matches all files beginning withc
*c
Matches all files ending withc
*c*
Matches all files that havec
in them (including at thebeginning or end).
To match hidden files (that start with a.
set theFile::FNM_DOTMATCH flag.
**
Matches directories recursively or files expansively.
?
Matches any one character. Equivalent to/.{1}/
in regexp.
[set]
Matches any one character inset
. Behaves exactly likecharacter sets inRegexp, including set negation([^a-z]
).
\
Escapes the next metacharacter.
{a,b}
Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled.Behaves like aRegexp union((?:a|b)
).
flags
is a bitwise OR of theFNM_XXX
constants.The same glob pattern and flags are used byDir.glob.
Examples:
File.fnmatch('cat','cat')#=> true # match entire stringFile.fnmatch('cat','category')#=> false # only match partial stringFile.fnmatch('c{at,ub}s','cats')#=> false # { } isn't supported by defaultFile.fnmatch('c{at,ub}s','cats',File::FNM_EXTGLOB)#=> true # { } is supported on FNM_EXTGLOBFile.fnmatch('c?t','cat')#=> true # '?' match only 1 characterFile.fnmatch('c??t','cat')#=> false # dittoFile.fnmatch('c*','cats')#=> true # '*' match 0 or more charactersFile.fnmatch('c*t','c/a/b/t')#=> true # dittoFile.fnmatch('ca[a-z]','cat')#=> true # inclusive bracket expressionFile.fnmatch('ca[^t]','cat')#=> false # exclusive bracket expression ('^' or '!')File.fnmatch('cat','CAT')#=> false # case sensitiveFile.fnmatch('cat','CAT',File::FNM_CASEFOLD)#=> true # case insensitiveFile.fnmatch('cat','CAT',File::FNM_SYSCASE)#=> true or false # depends on the system defaultFile.fnmatch('?','/',File::FNM_PATHNAME)#=> false # wildcard doesn't match '/' on FNM_PATHNAMEFile.fnmatch('*','/',File::FNM_PATHNAME)#=> false # dittoFile.fnmatch('[/]','/',File::FNM_PATHNAME)#=> false # dittoFile.fnmatch('\?','?')#=> true # escaped wildcard becomes ordinaryFile.fnmatch('\a','a')#=> true # escaped ordinary remains ordinaryFile.fnmatch('\a','\a',File::FNM_NOESCAPE)#=> true # FNM_NOESCAPE makes '\' ordinaryFile.fnmatch('[\?]','?')#=> true # can escape inside bracket expressionFile.fnmatch('*','.profile')#=> false # wildcard doesn't match leadingFile.fnmatch('*','.profile',File::FNM_DOTMATCH)#=> true # period by default.File.fnmatch('.*','.profile')#=> truerbfiles ='**''/''*.rb'# you don't have to do like this. just write in single string.File.fnmatch(rbfiles,'main.rb')#=> falseFile.fnmatch(rbfiles,'./main.rb')#=> falseFile.fnmatch(rbfiles,'lib/song.rb')#=> trueFile.fnmatch('**.rb','main.rb')#=> trueFile.fnmatch('**.rb','./main.rb')#=> falseFile.fnmatch('**.rb','lib/song.rb')#=> trueFile.fnmatch('*','dave/.profile')#=> truepattern ='*''/''*'File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME)#=> falseFile.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME|File::FNM_DOTMATCH)#=> truepattern ='**''/''foo'File.fnmatch(pattern,'a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'/a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'c:/a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME)#=> falseFile.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME|File::FNM_DOTMATCH)#=> true
static VALUEfile_s_fnmatch(int argc, VALUE *argv, VALUE obj){ VALUE pattern, path; VALUE rflags; int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) flags = NUM2INT(rflags); else flags = 0; StringValueCStr(pattern); FilePathStringValue(path); if (flags & FNM_EXTGLOB) { struct brace_args args; args.value = path; args.flags = flags; if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace, (VALUE)&args, rb_enc_get(pattern), pattern) > 0) return Qtrue; } else { rb_encoding *enc = rb_enc_compatible(pattern, path); if (!enc) return Qfalse; if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) return Qtrue; } RB_GC_GUARD(pattern); return Qfalse;}
Returns true ifpath
matches againstpattern
. The pattern is not a regular expression; instead it follows rules similarto shell filename globbing. It may contain the following metacharacters:
*
Matches any file. Can be restricted by other values in the glob. Equivalentto/ .* /x
in regexp.
*
Matches all files regular files
c*
Matches all files beginning withc
*c
Matches all files ending withc
*c*
Matches all files that havec
in them (including at thebeginning or end).
To match hidden files (that start with a.
set theFile::FNM_DOTMATCH flag.
**
Matches directories recursively or files expansively.
?
Matches any one character. Equivalent to/.{1}/
in regexp.
[set]
Matches any one character inset
. Behaves exactly likecharacter sets inRegexp, including set negation([^a-z]
).
\
Escapes the next metacharacter.
{a,b}
Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled.Behaves like aRegexp union((?:a|b)
).
flags
is a bitwise OR of theFNM_XXX
constants.The same glob pattern and flags are used byDir.glob.
Examples:
File.fnmatch('cat','cat')#=> true # match entire stringFile.fnmatch('cat','category')#=> false # only match partial stringFile.fnmatch('c{at,ub}s','cats')#=> false # { } isn't supported by defaultFile.fnmatch('c{at,ub}s','cats',File::FNM_EXTGLOB)#=> true # { } is supported on FNM_EXTGLOBFile.fnmatch('c?t','cat')#=> true # '?' match only 1 characterFile.fnmatch('c??t','cat')#=> false # dittoFile.fnmatch('c*','cats')#=> true # '*' match 0 or more charactersFile.fnmatch('c*t','c/a/b/t')#=> true # dittoFile.fnmatch('ca[a-z]','cat')#=> true # inclusive bracket expressionFile.fnmatch('ca[^t]','cat')#=> false # exclusive bracket expression ('^' or '!')File.fnmatch('cat','CAT')#=> false # case sensitiveFile.fnmatch('cat','CAT',File::FNM_CASEFOLD)#=> true # case insensitiveFile.fnmatch('cat','CAT',File::FNM_SYSCASE)#=> true or false # depends on the system defaultFile.fnmatch('?','/',File::FNM_PATHNAME)#=> false # wildcard doesn't match '/' on FNM_PATHNAMEFile.fnmatch('*','/',File::FNM_PATHNAME)#=> false # dittoFile.fnmatch('[/]','/',File::FNM_PATHNAME)#=> false # dittoFile.fnmatch('\?','?')#=> true # escaped wildcard becomes ordinaryFile.fnmatch('\a','a')#=> true # escaped ordinary remains ordinaryFile.fnmatch('\a','\a',File::FNM_NOESCAPE)#=> true # FNM_NOESCAPE makes '\' ordinaryFile.fnmatch('[\?]','?')#=> true # can escape inside bracket expressionFile.fnmatch('*','.profile')#=> false # wildcard doesn't match leadingFile.fnmatch('*','.profile',File::FNM_DOTMATCH)#=> true # period by default.File.fnmatch('.*','.profile')#=> truerbfiles ='**''/''*.rb'# you don't have to do like this. just write in single string.File.fnmatch(rbfiles,'main.rb')#=> falseFile.fnmatch(rbfiles,'./main.rb')#=> falseFile.fnmatch(rbfiles,'lib/song.rb')#=> trueFile.fnmatch('**.rb','main.rb')#=> trueFile.fnmatch('**.rb','./main.rb')#=> falseFile.fnmatch('**.rb','lib/song.rb')#=> trueFile.fnmatch('*','dave/.profile')#=> truepattern ='*''/''*'File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME)#=> falseFile.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME|File::FNM_DOTMATCH)#=> truepattern ='**''/''foo'File.fnmatch(pattern,'a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'/a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'c:/a/b/c/foo',File::FNM_PATHNAME)#=> trueFile.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME)#=> falseFile.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME|File::FNM_DOTMATCH)#=> true
static VALUEfile_s_fnmatch(int argc, VALUE *argv, VALUE obj){ VALUE pattern, path; VALUE rflags; int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) flags = NUM2INT(rflags); else flags = 0; StringValueCStr(pattern); FilePathStringValue(path); if (flags & FNM_EXTGLOB) { struct brace_args args; args.value = path; args.flags = flags; if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace, (VALUE)&args, rb_enc_get(pattern), pattern) > 0) return Qtrue; } else { rb_encoding *enc = rb_enc_compatible(pattern, path); if (!enc) return Qfalse; if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) return Qtrue; } RB_GC_GUARD(pattern); return Qfalse;}
Identifies the type of the named file; the return string is one of“file
'', “directory
'',“characterSpecial
'',“blockSpecial
'', “fifo
'',“link
'', “socket
'', or“unknown
''.
File.ftype("testfile")#=> "file"File.ftype("/dev/tty")#=> "characterSpecial"File.ftype("/tmp/.X11-unix/X0")#=> "socket"
static VALUErb_file_s_ftype(VALUE klass, VALUE fname){ struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname); } return rb_file_ftype(&st);}
Returnstrue
if the named file exists and the effective groupid of the calling process is the owner of the file. Returnsfalse
on Windows.
file_name can be anIO object.
static VALUErb_file_grpowned_p(VALUE obj, VALUE fname){#ifndef _WIN32 struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (rb_group_member(st.st_gid)) return Qtrue;#endif return Qfalse;}
Returnstrue
if the named files are identical.
file_1 andfile_2 can be anIOobject.
open("a","w") {}pFile.identical?("a","a")#=> truepFile.identical?("a","./a")#=> trueFile.link("a","b")pFile.identical?("a","b")#=> trueFile.symlink("a","c")pFile.identical?("a","c")#=> trueopen("d","w") {}pFile.identical?("a","d")#=> false
static VALUErb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2){#ifndef _WIN32 struct stat st1, st2; if (rb_stat(fname1, &st1) < 0) return Qfalse; if (rb_stat(fname2, &st2) < 0) return Qfalse; if (st1.st_dev != st2.st_dev) return Qfalse; if (st1.st_ino != st2.st_ino) return Qfalse; return Qtrue;#else extern VALUE rb_w32_file_identical_p(VALUE, VALUE); return rb_w32_file_identical_p(fname1, fname2);#endif}
Returns a new string formed by joining the strings using"/"
.
File.join("usr","mail","gumby")#=> "usr/mail/gumby"
static VALUErb_file_s_join(VALUE klass, VALUE args){ return rb_file_join(args);}
Equivalent to::chmod, but does notfollow symbolic links (so it will change the permissions associated withthe link, not the file referenced by the link). Often not available.
static VALUErb_file_s_lchmod(int argc, VALUE *argv, VALUE _){ mode_t mode; apply2args(1); mode = NUM2MODET(*argv++); return apply2files(lchmod_internal, argc, argv, &mode);}
Equivalent to::chown, but does notfollow symbolic links (so it will change the owner associated with thelink, not the file referenced by the link). Often not available. Returnsnumber of files in the argument list.
static VALUErb_file_s_lchown(int argc, VALUE *argv, VALUE _){ struct chown_args arg; apply2args(2); arg.owner = to_uid(*argv++); arg.group = to_gid(*argv++); return apply2files(lchown_internal, argc, argv, &arg);}
Creates a new name for an existing file using a hard link. Will notoverwritenew_name if it already exists (raising a subclass ofSystemCallError). Not available on allplatforms.
File.link("testfile",".testfile")#=> 0IO.readlines(".testfile")[0]#=> "This is line one\n"
static VALUErb_file_s_link(VALUE klass, VALUE from, VALUE to){ FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to); if (link(StringValueCStr(from), StringValueCStr(to)) < 0) { sys_fail2(from, to); } return INT2FIX(0);}
Same as::stat, but does not followthe last symbolic link. Instead, reports on the link itself.
File.symlink("testfile","link2test")#=> 0File.stat("testfile").size#=> 66File.lstat("link2test").size#=> 8File.stat("link2test").size#=> 66
static VALUErb_file_s_lstat(VALUE klass, VALUE fname){#ifdef HAVE_LSTAT struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname); } return rb_stat_new(&st);#else return rb_file_s_stat(klass, fname);#endif}
Sets the access and modification times of each named file to the first twoarguments. If a file is a symlink, this method acts upon the link itself asopposed to its referent; for the inverse behavior, see::utime. Returns the number of filenames in the argument list.
static VALUErb_file_s_lutime(int argc, VALUE *argv, VALUE _){ return utime_internal_i(argc, argv, TRUE);}
Creates a FIFO special file with namefile_name.modespecifies the FIFO's permissions. It is modified by the process'sumask in the usual way: the permissions of the created file are (mode &~umask).
static VALUErb_file_s_mkfifo(int argc, VALUE *argv, VALUE _){ VALUE path; struct mkfifo_arg ma; ma.mode = 0666; rb_check_arity(argc, 1, 2); if (argc > 1) { ma.mode = NUM2MODET(argv[1]); } path = argv[0]; FilePathValue(path); path = rb_str_encode_ospath(path); ma.path = RSTRING_PTR(path); if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) { rb_sys_fail_path(path); } return INT2FIX(0);}
Returns the modification time for the named file as aTime object.
file_name can be anIO object.
File.mtime("testfile")#=> Tue Apr 08 12:58:04 CDT 2003
static VALUErb_file_s_mtime(VALUE klass, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_mtime(&st);}
Opens the file named byfilename
according to the givenmode
and returns a newFile object.
SeeIO.new for a description ofmode
andopt
.
If a file is being created, permission bits may be given inperm
. These mode and permission bits are platform dependent;on Unix systems, see open(2) and chmod(2) man pages for details.
The newFile object is buffered mode (or non-syncmode), unlessfilename
is a tty. SeeIO#flush,IO#fsync,IO#fdatasync, andIO#sync= about sync mode.
f =File.new("testfile","r")f =File.new("newfile","w+")f =File.new("newfile",File::CREAT|File::TRUNC|File::RDWR,0644)
static VALUErb_file_initialize(int argc, VALUE *argv, VALUE io){ if (RFILE(io)->fptr) { rb_raise(rb_eRuntimeError, "reinitializing File"); } if (0 < argc && argc < 3) { VALUE fd = rb_check_to_int(argv[0]); if (!NIL_P(fd)) { argv[0] = fd; return rb_io_initialize(argc, argv, io); } } rb_open_file(argc, argv, io); return io;}
With no associated block,::open is asynonym for::new. If the optionalcode block is given, it will be passed the openedfile
as anargument and theFile object will automatically beclosed when the block terminates. The value of the block will be returnedfrom::open.
If a file is being created, its initial permissions may be set using theperm
parameter. See::new for further discussion.
SeeIO.new for a description of themode
andopt
parameters.
static VALUErb_io_s_open(int argc, VALUE *argv, VALUE klass){ VALUE io = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS); if (rb_block_given_p()) { return rb_ensure(rb_yield, io, io_close, io); } return io;}
Returnstrue
if the named file exists and the effective usedid of the calling process is the owner of the file.
file_name can be anIO object.
static VALUErb_file_owned_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (st.st_uid == geteuid()) return Qtrue; return Qfalse;}
Returns the string representation of the path
File.path("/dev/null")#=> "/dev/null"File.path(Pathname.new("/tmp"))#=> "/tmp"
static VALUErb_file_s_path(VALUE klass, VALUE fname){ return rb_get_path(fname);}
Returnstrue
if the named file is a pipe.
file_name can be anIO object.
static VALUErb_file_pipe_p(VALUE obj, VALUE fname){#ifdef S_IFIFO# ifndef S_ISFIFO# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)# endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISFIFO(st.st_mode)) return Qtrue;#endif return Qfalse;}
Returnstrue
if the named file is readable by the effectiveuser and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return trueeven though the file is not readable by the effective user/group.
static VALUErb_file_readable_p(VALUE obj, VALUE fname){ if (rb_eaccess(fname, R_OK) < 0) return Qfalse; return Qtrue;}
Returnstrue
if the named file is readable by the real userand group id of this process. See access(3).
Note that some OS-level security features may cause this to return trueeven though the file is not readable by the real user/group.
static VALUErb_file_readable_real_p(VALUE obj, VALUE fname){ if (rb_access(fname, R_OK) < 0) return Qfalse; return Qtrue;}
Returns the name of the file referenced by the given link. Not available onall platforms.
File.symlink("testfile","link2test")#=> 0File.readlink("link2test")#=> "testfile"
static VALUErb_file_s_readlink(VALUE klass, VALUE path){ return rb_readlink(path, rb_filesystem_encoding());}
Returns the real (absolute) pathname ofpathname in the actualfilesystem. The real pathname doesn't contain symlinks or useless dots.
Ifdir_string is given, it is used as a base directory forinterpreting relative pathname instead of the current directory.
The last component of the real pathname can be nonexistent.
static VALUErb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass){ VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil; VALUE path = argv[0]; FilePathValue(path); return rb_realpath_internal(basedir, path, 0);}
Returns the real (absolute) pathname ofpathname in the actualfilesystem not containing symlinks or useless dots.
Ifdir_string is given, it is used as a base directory forinterpreting relative pathname instead of the current directory.
All components of the pathname must exist when this method is called.
static VALUErb_file_s_realpath(int argc, VALUE *argv, VALUE klass){ VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil; VALUE path = argv[0]; FilePathValue(path); return rb_realpath_internal(basedir, path, 1);}
Renames the given file to the new name. Raises aSystemCallError if the file cannot berenamed.
File.rename("afile","afile.bak")#=> 0
static VALUErb_file_s_rename(VALUE klass, VALUE from, VALUE to){ struct rename_args ra; VALUE f, t; FilePathValue(from); FilePathValue(to); f = rb_str_encode_ospath(from); t = rb_str_encode_ospath(to); ra.src = StringValueCStr(f); ra.dst = StringValueCStr(t);#if defined __CYGWIN__ errno = 0;#endif if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra, RUBY_UBF_IO, 0) < 0) { int e = errno;#if defined DOSISH switch (e) { case EEXIST: if (chmod(ra.dst, 0666) == 0 && unlink(ra.dst) == 0 && rename(ra.src, ra.dst) == 0) return INT2FIX(0); }#endif syserr_fail2(e, from, to); } return INT2FIX(0);}
Returnstrue
if the named file has the setgid bit set.
file_name can be anIO object.
static VALUErb_file_sgid_p(VALUE obj, VALUE fname){#ifdef S_ISGID return check3rdbyte(fname, S_ISGID);#else return Qfalse;#endif}
Returnstrue
if the named file has the setuid bit set.
file_name can be anIO object.
static VALUErb_file_suid_p(VALUE obj, VALUE fname){#ifdef S_ISUID return check3rdbyte(fname, S_ISUID);#else return Qfalse;#endif}
Returns the size offile_name
.
file_name can be anIO object.
static VALUErb_file_s_size(VALUE klass, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return OFFT2NUM(st.st_size);}
Returnsnil
iffile_name
doesn't exist or haszero size, the size of the file otherwise.
file_name can be anIO object.
static VALUErb_file_size_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if (st.st_size == 0) return Qnil; return OFFT2NUM(st.st_size);}
Returnstrue
if the named file is a socket.
file_name can be anIO object.
static VALUErb_file_socket_p(VALUE obj, VALUE fname){#ifndef S_ISSOCK# ifdef _S_ISSOCK# define S_ISSOCK(m) _S_ISSOCK(m)# else# ifdef _S_IFSOCK# define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)# else# ifdef S_IFSOCK# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)# endif# endif# endif#endif#ifdef S_ISSOCK struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISSOCK(st.st_mode)) return Qtrue;#endif return Qfalse;}
Splits the given string into a directory and a file component and returnsthem in a two-element array. See also::dirname and::basename.
File.split("/home/gumby/.profile")#=> ["/home/gumby", ".profile"]
static VALUErb_file_s_split(VALUE klass, VALUE path){ FilePathStringValue(path); /* get rid of converting twice */ return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));}
Returns aFile::Stat object for the named file(seeFile::Stat).
File.stat("testfile").mtime#=> Tue Apr 08 12:58:04 CDT 2003
static VALUErb_file_s_stat(VALUE klass, VALUE fname){ struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) { rb_sys_fail_path(fname); } return rb_stat_new(&st);}
Returnstrue
if the named file has the sticky bit set.
file_name can be anIO object.
static VALUErb_file_sticky_p(VALUE obj, VALUE fname){#ifdef S_ISVTX return check3rdbyte(fname, S_ISVTX);#else return Qnil;#endif}
Creates a symbolic link callednew_name for the existing fileold_name. Raises a NotImplemented exception on platforms that donot support symbolic links.
File.symlink("testfile","link2test")#=> 0
static VALUErb_file_s_symlink(VALUE klass, VALUE from, VALUE to){ FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to); if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) { sys_fail2(from, to); } return INT2FIX(0);}
Returnstrue
if the named file is a symbolic link.
static VALUErb_file_symlink_p(VALUE obj, VALUE fname){#ifndef S_ISLNK# ifdef _S_ISLNK# define S_ISLNK(m) _S_ISLNK(m)# else# ifdef _S_IFLNK# define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)# else# ifdef S_IFLNK# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)# endif# endif# endif#endif#ifdef S_ISLNK struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse; if (S_ISLNK(st.st_mode)) return Qtrue;#endif return Qfalse;}
Truncates the filefile_name to be at mostinteger byteslong. Not available on all platforms.
f =File.new("out","w")f.write("1234567890")#=> 10f.close#=> nilFile.truncate("out",5)#=> 0File.size("out")#=> 5
static VALUErb_file_s_truncate(VALUE klass, VALUE path, VALUE len){ struct truncate_arg ta; int r; ta.pos = NUM2POS(len); FilePathValue(path); path = rb_str_encode_ospath(path); ta.path = StringValueCStr(path); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta, RUBY_UBF_IO, NULL); if (r < 0) rb_sys_fail_path(path); return INT2FIX(0);#undef NUM2POS}
Returns the current umask value for this process. If the optional argumentis given, set the umask to that value and return the previous value. Umaskvalues aresubtracted from the default permissions, so a umask of0222
would make a file read-only for everyone.
File.umask(0006)#=> 18File.umask#=> 6
static VALUErb_file_s_umask(int argc, VALUE *argv, VALUE _){ mode_t omask = 0; switch (argc) { case 0: omask = umask(0); umask(omask); break; case 1: omask = umask(NUM2MODET(argv[0])); break; default: rb_error_arity(argc, 0, 1); } return MODET2NUM(omask);}
Deletes the named files, returning the number of names passed as arguments.Raises an exception on any error. Since the underlying implementationrelies on theunlink(2)
system call, the type of exceptionraised depends on its error type (seelinux.die.net/man/2/unlink)and has the form of e.g. Errno::ENOENT.
See alsoDir.rmdir.
static VALUErb_file_s_unlink(int argc, VALUE *argv, VALUE klass){ return apply2files(unlink_internal, argc, argv, 0);}
Sets the access and modification times of each named file to the first twoarguments. If a file is a symlink, this method acts upon its referentrather than the link itself; for the inverse behavior see::lutime. Returns the number of filenames in the argument list.
static VALUErb_file_s_utime(int argc, VALUE *argv, VALUE _){ return utime_internal_i(argc, argv, FALSE);}
Iffile_name is readable by others, returns an integerrepresenting the file permission bits offile_name. Returnsnil
otherwise. The meaning of the bits is platform dependent;on Unix systems, seestat(2)
.
file_name can be anIO object.
File.world_readable?("/etc/passwd")#=> 420m =File.world_readable?("/etc/passwd")sprintf("%o",m)#=> "644"
static VALUErb_file_world_readable_p(VALUE obj, VALUE fname){#ifdef S_IROTH struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IROTH)) == S_IROTH) { return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); }#endif return Qnil;}
Iffile_name is writable by others, returns an integerrepresenting the file permission bits offile_name. Returnsnil
otherwise. The meaning of the bits is platform dependent;on Unix systems, seestat(2)
.
file_name can be anIO object.
File.world_writable?("/tmp")#=> 511m =File.world_writable?("/tmp")sprintf("%o",m)#=> "777"
static VALUErb_file_world_writable_p(VALUE obj, VALUE fname){#ifdef S_IWOTH struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IWOTH)) == S_IWOTH) { return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); }#endif return Qnil;}
Returnstrue
if the named file is writable by the effectiveuser and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return trueeven though the file is not writable by the effective user/group.
static VALUErb_file_writable_p(VALUE obj, VALUE fname){ if (rb_eaccess(fname, W_OK) < 0) return Qfalse; return Qtrue;}
Returnstrue
if the named file is writable by the real userand group id of this process. See access(3).
Note that some OS-level security features may cause this to return trueeven though the file is not writable by the real user/group.
static VALUErb_file_writable_real_p(VALUE obj, VALUE fname){ if (rb_access(fname, W_OK) < 0) return Qfalse; return Qtrue;}
Returnstrue
if the named file exists and has a zero size.
file_name can be anIO object.
static VALUErb_file_zero_p(VALUE obj, VALUE fname){ struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (st.st_size == 0) return Qtrue; return Qfalse;}
Returns the last access time (aTime object) forfile, or epoch iffile has not been accessed.
File.new("testfile").atime#=> Wed Dec 31 18:00:00 CST 1969
static VALUErb_file_atime(VALUE obj){ rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_atime(&st);}
Returns the birth time forfile.
File.new("testfile").birthtime#=> Wed Apr 09 08:53:14 CDT 2003
If the platform doesn't have birthtime, raisesNotImplementedError.
static VALUErb_file_birthtime(VALUE obj){ rb_io_t *fptr; statx_data st; GetOpenFile(obj, fptr); if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) { rb_sys_fail_path(fptr->pathv); } return statx_birthtime(&st, fptr->pathv);}
Changes permission bits onfile to the bit pattern represented bymode_int. Actual effects are platform dependent; on Unix systems,seechmod(2)
for details. Follows symbolic links. Also seeFile#lchmod.
f =File.new("out","w");f.chmod(0644)#=> 0
static VALUErb_file_chmod(VALUE obj, VALUE vmode){ rb_io_t *fptr; mode_t mode;#if !defined HAVE_FCHMOD || !HAVE_FCHMOD VALUE path;#endif mode = NUM2MODET(vmode); GetOpenFile(obj, fptr);#ifdef HAVE_FCHMOD if (fchmod(fptr->fd, mode) == -1) { if (HAVE_FCHMOD || errno != ENOSYS) rb_sys_fail_path(fptr->pathv); } else { if (!HAVE_FCHMOD) return INT2FIX(0); }#endif#if !defined HAVE_FCHMOD || !HAVE_FCHMOD if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chmod(RSTRING_PTR(path), mode) == -1) rb_sys_fail_path(fptr->pathv);#endif return INT2FIX(0);}
Changes the owner and group offile to the given numeric owner andgroup id's. Only a process with superuser privileges may change theowner of a file. The current owner of a file may change the file'sgroup to any group to which the owner belongs. Anil
or -1owner or group id is ignored. Follows symbolic links. See also File#lchown.
File.new("testfile").chown(502,1000)
static VALUErb_file_chown(VALUE obj, VALUE owner, VALUE group){ rb_io_t *fptr; rb_uid_t o; rb_gid_t g;#ifndef HAVE_FCHOWN VALUE path;#endif o = to_uid(owner); g = to_gid(group); GetOpenFile(obj, fptr);#ifndef HAVE_FCHOWN if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chown(RSTRING_PTR(path), o, g) == -1) rb_sys_fail_path(fptr->pathv);#else if (fchown(fptr->fd, o, g) == -1) rb_sys_fail_path(fptr->pathv);#endif return INT2FIX(0);}
Returns the change time forfile (that is, the time directoryinformation about the file was changed, not the file itself).
Note that on Windows (NTFS), returns creation time (birth time).
File.new("testfile").ctime#=> Wed Apr 09 08:53:14 CDT 2003
static VALUErb_file_ctime(VALUE obj){ rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_ctime(&st);}
Locks or unlocks a file according tolocking_constant (a logicalor of the values in the table below). Returnsfalse
if File::LOCK_NB is specified and the operation would otherwise haveblocked. Not available on all platforms.
Locking constants (in classFile):
LOCK_EX | Exclusive lock. Only one process may hold an | exclusive lock for a given file at a time.----------+------------------------------------------------LOCK_NB | Don't block when locking. May be combined | with other lock options using logical or.----------+------------------------------------------------LOCK_SH | Shared lock. Multiple processes may each hold a | shared lock for a given file at the same time.----------+------------------------------------------------LOCK_UN | Unlock.
Example:
# update a counter using write lock# don't use "w" because it truncates the file before lock.File.open("counter",File::RDWR|File::CREAT,0644) {|f|f.flock(File::LOCK_EX)value =f.read.to_i+1f.rewindf.write("#{value}\n")f.flushf.truncate(f.pos)}# read the counter using read lockFile.open("counter","r") {|f|f.flock(File::LOCK_SH)pf.read}
static VALUErb_file_flock(VALUE obj, VALUE operation){ rb_io_t *fptr; int op[2], op1; struct timeval time; op[1] = op1 = NUM2INT(operation); GetOpenFile(obj, fptr); op[0] = fptr->fd; if (fptr->mode & FMODE_WRITABLE) { rb_io_flush_raw(obj, 0); } while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) { int e = errno; switch (e) { case EAGAIN: case EACCES:#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK:#endif if (op1 & LOCK_NB) return Qfalse; time.tv_sec = 0; time.tv_usec = 100 * 1000; /* 0.1 sec */ rb_thread_wait_for(time); rb_io_check_closed(fptr); continue; case EINTR:#if defined(ERESTART) case ERESTART:#endif break; default: rb_syserr_fail_path(e, fptr->pathv); } } return INT2FIX(0);}
Same asIO#stat, but does not followthe last symbolic link. Instead, reports on the link itself.
File.symlink("testfile","link2test")#=> 0File.stat("testfile").size#=> 66f =File.new("link2test")f.lstat.size#=> 8f.stat.size#=> 66
static VALUErb_file_lstat(VALUE obj){#ifdef HAVE_LSTAT rb_io_t *fptr; struct stat st; VALUE path; GetOpenFile(obj, fptr); if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) { rb_sys_fail_path(fptr->pathv); } return rb_stat_new(&st);#else return rb_io_stat(obj);#endif}
Returns the modification time forfile.
File.new("testfile").mtime#=> Wed Apr 09 08:53:14 CDT 2003
static VALUErb_file_mtime(VALUE obj){ rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_mtime(&st);}
Returns the pathname used to createfile as a string. Does notnormalize the name.
The pathname may not point to the file corresponding tofile. Forinstance, the pathname becomes void when the file has been moved ordeleted.
This method raisesIOError for afilecreated using File::Constants::TMPFILE because they don't have apathname.
File.new("testfile").path#=> "testfile"File.new("/tmp/../tmp/xxx","w").path#=> "/tmp/../tmp/xxx"
static VALUErb_file_path(VALUE obj){ rb_io_t *fptr; fptr = RFILE(rb_io_taint_check(obj))->fptr; rb_io_check_initialized(fptr); if (NIL_P(fptr->pathv)) { rb_raise(rb_eIOError, "File is unnamed (TMPFILE?)"); } return rb_str_dup(fptr->pathv);}
Returns the size offile in bytes.
File.new("testfile").size#=> 66
static VALUErb_file_size(VALUE obj){ rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fptr->mode & FMODE_WRITABLE) { rb_io_flush_raw(obj, 0); } if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return OFFT2NUM(st.st_size);}
Returns the pathname used to createfile as a string. Does notnormalize the name.
The pathname may not point to the file corresponding tofile. Forinstance, the pathname becomes void when the file has been moved ordeleted.
This method raisesIOError for afilecreated using File::Constants::TMPFILE because they don't have apathname.
File.new("testfile").path#=> "testfile"File.new("/tmp/../tmp/xxx","w").path#=> "/tmp/../tmp/xxx"
static VALUErb_file_path(VALUE obj){ rb_io_t *fptr; fptr = RFILE(rb_io_taint_check(obj))->fptr; rb_io_check_initialized(fptr); if (NIL_P(fptr->pathv)) { rb_raise(rb_eIOError, "File is unnamed (TMPFILE?)"); } return rb_str_dup(fptr->pathv);}
Truncatesfile to at mostinteger bytes. The file must beopened for writing. Not available on all platforms.
f =File.new("out","w")f.syswrite("1234567890")#=> 10f.truncate(5)#=> 0f.close()#=> nilFile.size("out")#=> 5
static VALUErb_file_truncate(VALUE obj, VALUE len){ rb_io_t *fptr; struct ftruncate_arg fa; fa.pos = NUM2POS(len); GetOpenFile(obj, fptr); if (!(fptr->mode & FMODE_WRITABLE)) { rb_raise(rb_eIOError, "not opened for writing"); } rb_io_flush_raw(obj, 0); fa.fd = fptr->fd; if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) { rb_sys_fail_path(fptr->pathv); } return INT2FIX(0);#undef NUM2POS}
This page was generated for Ruby 3.0.0
Generated with Ruby-doc Rdoc Generator 0.42.0.