在线文档教程
Ruby 2.4

File

class File

Parent:IO

File是程序可访问的任何文件对象的抽象,并且与类紧密相关IOFile包括模块方法FileTest作为类方法,允许你写(例如)File.exist?("foo")

在文件方法的描述中,权限位是指示文件权限的特定于平台的一组位。在基于Unix的系统上,对于所有者,组和世界其他地方,权限被视为一组三个八位字节。对于这些实体中的每一个,都可以将权限设置为读取,写入或执行文件:

权限位0644(八进制)因此将被解释为所有者的读/写,并且对于组和其他的只读。高位也可以用来指示文件的类型(普通,目录,管道,套接字等等)和各种其他特殊功能。如果权限是针对目录的,则执行位的含义会改变; 当设置目录可以被搜索。

在非Posix操作系统上,可能只能将文件设置为只读或读写。在这种情况下,剩余的许可位将被合成为与典型值相似。例如,在Windows NT上,默认权限位是0644,这意味着对所有者的读/写,对于其他所有者是只读的。唯一可以做的改变是使文件是只读的,这被报告为0444

File中的方法的各种常量可以在File::Constants中找到。

常量

ALT_SEPARATOR

平台特定的替代分隔符

PATH_SEPARATOR

路径列表分隔符

SEPARATOR Separator

分离路径中的目录部分

公共分类方法

absolute_path(file_name , dir_string ) → abs_file_name Show source

将路径名转换为绝对路径名。除非给出dir_string,否则相对路径将从进程的当前工作目录中引用,在这种情况下,它将用作起点。如果给定的路径名​​以“ ~” 开头,则不会展开,它将被视为正常的目录名称。

File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"

VALUE rb_file_s_absolute_path(int argc, const VALUE *argv) { rb_check_arity(argc, 1, 2 return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil }

atime(file_name) → time Show source

以Time对象的形式返回指定文件的上次访问时间)。

file_name can be an IO object.

File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003

static VALUE rb_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 }

basename(file_name , suffix ) → base_name Show source

返回file_name中给出的文件名的最后一个组件,可以使用两者形成File::SEPARATORFile::ALT_SEPARATORFile::ALT_SEPARATOR不是时则作为分隔符nil。如果给出后缀并存在于file_name的末尾,则会将其删除。如果后缀是“。*”,则任何扩展名将被删除。

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 VALUE rb_file_s_basename(int argc, VALUE *argv) { 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 OBJ_INFECT(basename, fname return basename; }

birthtime(file_name) → time Show source

返回指定文件的出生时间。

file_name can be an IO object.

File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003

如果平台没有生日,则引发NotImplementedError。

static VALUE rb_file_s_birthtime(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_birthtime(&st }

blockdev?(file_name) → true or false Show source

如果指定文件是块设备,则返回true

file_name can be an IO object.

static VALUE rb_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; }

chardev?(file_name) → true or false Show source

如果指定的文件是字符设备,则返回true

file_name can be an IO object.

static VALUE rb_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; }

chmod(mode_int, file_name, ... ) → integer Show source

将指定文件的权限位更改为由mode_int表示的位模式。实际影响取决于操作系统(参见本节的开头部分)。在Unix系统上,请参阅chmod(2)详细信息。返回处理的文件数量。

File.chmod(0644, "testfile", "out") #=> 2

static VALUE rb_file_s_chmod(int argc, VALUE *argv) { int mode; apply2args(1 mode = NUM2INT(*argv++ return apply2files(chmod_internal, argc, argv, &mode }

chown(owner_int, group_int, file_name,... ) → integer Show source

将指定文件的所有者和组更改为给定的数字所有者和组ID。只有具有超级用户权限的进程才能更改文件的所有者。文件的当前所有者可能会将文件的组更改为所有者所属的任何组。nil或-1所有者或组ID将被忽略。返回处理的文件数量。

File.chown(nil, 100, "testfile")

static VALUE rb_file_s_chown(int argc, VALUE *argv) { struct chown_args arg; apply2args(2 arg.owner = to_uid(*argv++ arg.group = to_gid(*argv++ return apply2files(chown_internal, argc, argv, &arg }

ctime(file_name) → time Show source

返回指定文件的更改时间(有关文件的目录信息发生更改的时间,而不是文件本身)。

file_name can be an IO object.

请注意,在Windows(NTFS)上返回创建时间(出生时间)。

File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003

static VALUE rb_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 }

delete(file_name, ...) → integer Show source

删除指定的文件,返回作为参数传递的名称数量。发生任何错误都会引发异常。另见Dir::rmdir

static VALUE rb_file_s_unlink(int argc, VALUE *argv, VALUE klass) { return apply2files(unlink_internal, argc, argv, 0 }

directory?(file_name) → true or false Show source

如果指定的文件是目录或指向目录的符号链接,则返回true;否则返回false

file_name can be an IO object.

File.directory?(".")

VALUE rb_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; }

dirname(file_name) → dir_name Show source

返回file_name中给出的文件名中除最后一个之外的所有组件。文件名可以使用两者形成File::SEPARATORFile::ALT_SEPARATORFile::ALT_SEPARATOR不是时可以使用分隔符nil

File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"

static VALUE rb_file_s_dirname(VALUE klass, VALUE fname) { return rb_file_dirname(fname }

zero?(file_name) → true or false Show source

返回true指定文件是否存在且大小为零。

file_name can be an IO object.

static VALUE rb_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; }

executable?(file_name) → true or false Show source

返回true指定文件是否可由此进程的有效用户和组标识执行。参见eaccess(3)。

static VALUE rb_file_executable_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (eaccess(StringValueCStr(fname), X_OK) < 0) return Qfalse; return Qtrue; }

executable_real?(file_name) → true or false Show source

如果指定文件可由此进程的实际用户和组标识执行,则返回true。请参阅访问权限(3)。

static VALUE rb_file_executable_real_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (access(StringValueCStr(fname), X_OK) < 0) return Qfalse; return Qtrue; }

exist?(file_name) → true or false Show source

如果指定的文件存在,则返回true

file_name can be an IO object.

“文件存在”意味着stat()或fstat()系统调用成功。

static VALUE rb_file_exist_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return Qtrue; }

exists?(file_name) → true or false Show source

弃用的方法。不要使用。

static VALUE rb_file_exists_p(VALUE obj, VALUE fname) { const char *s = "FileTest#"; if (obj == rb_mFileTest) { s = "FileTest."; } else if (obj == rb_cFile || (RB_TYPE_P(obj, T_CLASS) && RTEST(rb_class_inherited_p(obj, rb_cFile)))) { s = "File."; } rb_warning("%sexists? is a deprecated name, use %sexist? instead", s, s return rb_file_exist_p(obj, fname }

expand_path(file_name , dir_string ) → abs_file_name Show source

将路径名转换为绝对路径名。除非dir_string给出相对路径,否则将从当前进程的工作目录引用相对路径,在这种情况下,它将用作起点。给定的路径名​​可以以“ ~' 开头,该扩展到流程所有者的主目录(环境变量HOME必须正确设置)。“ ~用户 ”扩展到指定用户的主目录。

File.expand_path("~oracle/bin") #=> "/home/oracle/bin"

一个简单的使用例子dir_string如下。

File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"

解析父目录的更复杂的例子如下。假设我们在bin/mygem中,并且需要lib/mygem.rb的绝对路径。

File.expand_path("../../lib/mygem.rb", __FILE__) #=> ".../path/to/project/lib/mygem.rb"

所以首先解决__FILE__的父级,即bin/,然后转到父项,即项目的根目录并追加lib/mygem.rb

VALUE rb_file_s_expand_path(int argc, const VALUE *argv) { rb_check_arity(argc, 1, 2 return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil }

extname(path) → string Show source

返回扩展名(path从上一段开始的文件名部分)。

如果path是点文件,或者以句点开头,则起始点不处理扩展的开始。

当句点是最后一个字符时,也会返回一个空字符串path

File.extname("test.rb") #=> ".rb" File.extname("a/b/d/test.rb") #=> ".rb" File.extname(".a/b/d/test.rb") #=> ".rb" File.extname("foo.") #=> "" File.extname("test") #=> "" File.extname(".profile") #=> "" File.extname(".profile.sh") #=> ".sh"

static VALUE rb_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! */ OBJ_INFECT(extname, fname return extname; }

file?(file) → true or false Show source

返回名称true是否file存在并且是常规文件。

file 可以是IO对象。

如果file参数是符号链接,它将解析符号链接并使用链接引用的文件。

static VALUE rb_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; }

fnmatch( pattern, path, flags ) → (true or false) Show source

fnmatch?( pattern, path, flags ) → (true or false)

如果path匹配,则返回true pattern。该模式不是一个正则表达式;相反,它遵循类似于shell文件名匹配的规则。它可能包含以下元字符:

*

匹配任何文件。可以被glob中的其他值限制。等同/ .* /x于正则表达式。

*

匹配所有文件的常规文件

c*

匹配以c开头的所有文件

*c

匹配以c结尾的所有文件 。

*c*

匹配其中的所有文件c(包括开头或结尾)。

匹配隐藏文件(以.设置File :: FNM_DOTMATCH标志开头)。

**

递归匹配目录或扩展性地匹配文件。

?

匹配任何一个字符。等同/.{1}/于正则表达式。

[set]

匹配任何一个字符set。行为与Regexp中的字符集完全相同,包括集合negation([^a-z])。

`\`

转义下一个元字符。

{a,b}

如果启用File::FNM_EXTGLOB标志,则匹配模式a和模式b。行为像一个正则表达式联合((?:a|b))。

flagsFNM_XXX常数的按位或。Dir.glob使用相同的全局模式和标志。

例子:

File.fnmatch('cat', 'cat') #=> true # match entire string File.fnmatch('cat', 'category') #=> false # only match partial string File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character File.fnmatch('c??t', 'cat') #=> false # ditto File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!') File.fnmatch('cat', 'CAT') #=> false # case sensitive File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default. File.fnmatch('.*', '.profile') #=> true rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string. File.fnmatch(rbfiles, 'main.rb') #=> false File.fnmatch(rbfiles, './main.rb') #=> false File.fnmatch(rbfiles, 'lib/song.rb') #=> true File.fnmatch('**.rb', 'main.rb') #=> true File.fnmatch('**.rb', './main.rb') #=> false File.fnmatch('**.rb', 'lib/song.rb') #=> true File.fnmatch('*', 'dave/.profile') #=> true pattern = '*' '/' '*' File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true pattern = '**' '/' 'foo' File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true

static VALUE file_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; StringValue(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)) > 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; }

fnmatch?( pattern, path, flags ) → (true or false) Show source

如果path匹配,则返回true pattern。该模式不是一个正则表达式; 相反,它遵循类似于shell文件名匹配的规则。它可能包含以下元字符:

*

匹配任何文件。可以被glob中的其他值限制。等同/ .* /x于正则表达式。

*

匹配所有文件的常规文件

c*

匹配以c开头的所有文件 。

*c

匹配以c结尾的所有文件 。

*c*

匹配其中的所有文件c(包括开头或结尾)。

匹配隐藏文件(以.设置File::FNM_DOTMATCH标志开头)。

**

递归匹配目录或扩展性地匹配文件。

?

匹配任何一个字符。等同/.{1}/于正则表达式。

[set]

匹配任何一个字符set。行为与Regexp中的字符集完全相同,包括集合negation([^a-z])。

`\`

转义下一个元字符。

{a,b}

如果启用File::FNM_EXTGLOB标志,则匹配模式a和模式b。行为像一个正则表达式联合((?:a|b))。

flagsFNM_XXX常数的按位或。Dir.glob使用相同的全局模式和标志。

例子:

File.fnmatch('cat', 'cat') #=> true # match entire string File.fnmatch('cat', 'category') #=> false # only match partial string File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character File.fnmatch('c??t', 'cat') #=> false # ditto File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!') File.fnmatch('cat', 'CAT') #=> false # case sensitive File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default. File.fnmatch('.*', '.profile') #=> true rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string. File.fnmatch(rbfiles, 'main.rb') #=> false File.fnmatch(rbfiles, './main.rb') #=> false File.fnmatch(rbfiles, 'lib/song.rb') #=> true File.fnmatch('**.rb', 'main.rb') #=> true File.fnmatch('**.rb', './main.rb') #=> false File.fnmatch('**.rb', 'lib/song.rb') #=> true File.fnmatch('*', 'dave/.profile') #=> true pattern = '*' '/' '*' File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true pattern = '**' '/' 'foo' File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true

static VALUE file_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; StringValue(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)) > 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; }

ftype(file_name) → string Show source

标识指定文件的类型; 返回字符串是file“',directory''',characterSpecial''',blockSpecial''',fifo''',link''',socket'''或unknown'''中的一个。

File.ftype("testfile") #=> "file" File.ftype("/dev/tty") #=> "characterSpecial" File.ftype("/tmp/.X11-unix/X0") #=> "socket"

static VALUE rb_file_s_ftype(VALUE klass, VALUE fname) { struct stat st; FilePathValue(fname fname = rb_str_encode_ospath(fname if (lstat(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname } return rb_file_ftype(&st }

grpowned?(file_name) → true or false Show source

返回true指定文件是否存在,并且调用进程的有效组标识是文件的所有者。false在Windows上返回。

file_name可以是IO对象。

static VALUE rb_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; }

identical?(file_1, file_2) → true or false Show source

如果命名文件相同则返回true

file_1file_2可以是IO对象。

open("a", "w") {} p File.identical?("a", "a") #=> true p File.identical?("a", "./a") #=> true File.link("a", "b") p File.identical?("a", "b") #=> true File.symlink("a", "c") p File.identical?("a", "c") #=> true open("d", "w") {} p File.identical?("a", "d") #=> false

static VALUE rb_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 BY_HANDLE_FILE_INFORMATION st1, st2; HANDLE f1 = 0, f2 = 0; f1 = w32_io_info(&fname1, &st1 if (f1 == INVALID_HANDLE_VALUE) return Qfalse; if (f1) { struct w32_io_info_args arg; arg.fname = &fname2; arg.st = &st2; f2 = (HANDLE)rb_ensure(call_w32_io_info, (VALUE)&arg, close_handle, (VALUE)f1 } else { f2 = w32_io_info(&fname2, &st2 } if (f2 == INVALID_HANDLE_VALUE) return Qfalse; if (f2) CloseHandle(f2 if (st1.dwVolumeSerialNumber == st2.dwVolumeSerialNumber && st1.nFileIndexHigh == st2.nFileIndexHigh && st1.nFileIndexLow == st2.nFileIndexLow) return Qtrue; return Qfalse; #endif }

join(string, ...) → string Show source

返回使用连接字符串形成的新字符串File::SEPARATOR

File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"

static VALUE rb_file_s_join(VALUE klass, VALUE args) { return rb_file_join(args, separator }

lchmod(mode_int, file_name, ...) → integer Show source

等同于File::chmod,但不遵循符号链接(因此它将更改与链接相关的权限,而不是链接引用的文件)。通常不可用。

static VALUE rb_file_s_lchmod(int argc, VALUE *argv) { long mode; apply2args(1 mode = NUM2INT(*argv++ return apply2files(lchmod_internal, argc, argv, (void *)(long)mode }

lchown(owner_int, group_int, file_name,..) → integer Show source

等同于File::chown但不遵循符号链接(因此它将更改与链接关联的所有者,而不是链接引用的文件)。通常不可用。返回参数列表中的文件数量。

static VALUE rb_file_s_lchown(int argc, VALUE *argv) { struct chown_args arg; apply2args(2 arg.owner = to_uid(*argv++ arg.group = to_gid(*argv++ return apply2files(lchown_internal, argc, argv, &arg }

link(old_name, new_name) → 0 Show source

使用硬链接为现有文件创建一个新名称。不会覆盖NEW_NAME如果它已经存在(提高的一个子类SystemCallError)。不适用于所有平台。

File.link("testfile", ".testfile") #=> 0 IO.readlines(".testfile")[0] #=> "This is line one\n"

static VALUE rb_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 }

lstat(file_name) → stat Show source

与之相同File::stat,但不遵循最后的符号链接。相反,报告链接本身。

File.symlink("testfile", "link2test") #=> 0 File.stat("testfile").size #=> 66 File.lstat("link2test").size #=> 8 File.stat("link2test").size #=> 66

static VALUE rb_file_s_lstat(VALUE klass, VALUE fname) { #ifdef HAVE_LSTAT struct stat st; FilePathValue(fname fname = rb_str_encode_ospath(fname if (lstat(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname } return rb_stat_new(&st #else return rb_file_s_stat(klass, fname #endif }

mkfifo(*args) Show source

static VALUE rb_file_s_mkfifo(int argc, VALUE *argv) { VALUE path; int mode = 0666; rb_check_arity(argc, 1, 2 if (argc > 1) { mode = NUM2INT(argv[1] } path = argv[0]; FilePathValue(path path = rb_str_encode_ospath(path if (mkfifo(RSTRING_PTR(path), mode)) { rb_sys_fail_path(path } return INT2FIX(0 }

mtime(file_name) → time Show source

以Time对象的形式返回指定文件的修改时间。

file_name可以是IO对象。

File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003

static VALUE rb_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 }

new(filename, mode="r" , opt) → file Show source

new(filename , mode [, perm]) → file

filename根据给定打开名为的文件mode并返回一个新的File对象。

See IO.new for a description of mode and opt.

如果正在创建一个文件,可能会给出权限位perm。这些模式和权限位依赖于平台; 在Unix系统上,请参阅open(2)和chmod(2)手册页以获取详细信息。

示例

f = File.new("testfile", "r") f = File.new("newfile", "w+") f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)

static VALUE rb_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; }

open(filename, mode="r" , opt) → file Show source

open(filename , mode [, perm]) → file

open(filename, mode="r" , opt) {|file| block } → obj

open(filename , mode [, perm]) {|file| block } → obj

没有关联的块,File.open是:: new的同义词。如果给出了可选的代码块,它将file作为参数传递并打开,当块终止时,File对象将自动关闭。该块的值将从中返回File.open

如果正在创建文件,则可以使用该perm参数设置其初始权限。请参阅:新进行进一步讨论。

见IO.new为的描述modeopt参数。

static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass) { VALUE io = rb_class_new_instance(argc, argv, klass if (rb_block_given_p()) { return rb_ensure(rb_yield, io, io_close, io } return io; }

owned?(file_name) → true or false Show source

返回true指定文件是否存在,并且调用进程的有效使用ID是文件的所有者。

file_name可以是IO对象。

static VALUE rb_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; }

path(path) → string Show source

返回路径的字符串表示形式

File.path("/dev/null") #=> "/dev/null" File.path(Pathname.new("/tmp")) #=> "/tmp"

static VALUE rb_file_s_path(VALUE klass, VALUE fname) { return rb_get_path(fname }

pipe?(file_name) → true or false Show source

返回true指定文件是否为pipe。

file_name可以是IO对象。

static VALUE rb_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; }

readable?(file_name) → true or false Show source

返回true指定文件是否可由此进程的有效用户和组标识读取。参见eaccess(3)。

static VALUE rb_file_readable_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (eaccess(StringValueCStr(fname), R_OK) < 0) return Qfalse; return Qtrue; }

readable_real?(file_name) → true or false Show source

返回true指定文件是否可由此进程的实际用户和组标识读取。请参阅访问权限(3)。

static VALUE rb_file_readable_real_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (access(StringValueCStr(fname), R_OK) < 0) return Qfalse; return Qtrue; }

readlink(link_name) → file_name Show source

返回给定链接引用的文件的名称。不适用于所有平台。

File.symlink("testfile", "link2test") #=> 0 File.readlink("link2test") #=> "testfile"

static VALUE rb_file_s_readlink(VALUE klass, VALUE path) { return rb_readlink(path, rb_filesystem_encoding() }

realdirpath(pathname , dir_string) → real_pathname Show source

返回实际文件系统中路径名的实际(绝对)路径名。真正的路径名不包含符号链接或无用点。

如果给出dir_string,它将用作解释相对路径名而不是当前目录的基本目录。

真实路径名的最后一个组件可能不存在。

static VALUE rb_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 }

realpath(pathname , dir_string) → real_pathname Show source

返回实际文件系统中不包含符号链接或无用点的路径名的真实(绝对)路径名

如果给出dir_string,它将用作解释相对路径名而不是当前目录的基本目录。

调用此方法时,路径名的所有组件都必须存在。

static VALUE rb_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 }

rename(old_name, new_name) → 0 Show source

将给定文件重命名为新名称。SystemCallError如果文件无法重命名,则引发一次。

File.rename("afile", "afile.bak") #=> 0

static VALUE rb_file_s_rename(VALUE klass, VALUE from, VALUE to) { const char *src, *dst; VALUE f, t; FilePathValue(from FilePathValue(to f = rb_str_encode_ospath(from t = rb_str_encode_ospath(to src = StringValueCStr(f dst = StringValueCStr(t #if defined __CYGWIN__ errno = 0; #endif if (rename(src, dst) < 0) { int e = errno; #if defined DOSISH switch (e) { case EEXIST: if (chmod(dst, 0666) == 0 && unlink(dst) == 0 && rename(src, dst) == 0) return INT2FIX(0 } #endif syserr_fail2(e, from, to } return INT2FIX(0 }

setgid?(file_name) → true or false Show source

返回true指定文件是否设置了setgid位。

static VALUE rb_file_sgid_p(VALUE obj, VALUE fname) { #ifdef S_ISGID return check3rdbyte(fname, S_ISGID #else return Qfalse; #endif }

setuid?(file_name) → true or false Show source

返回true指定文件是否设置了setuid位。

static VALUE rb_file_suid_p(VALUE obj, VALUE fname) { #ifdef S_ISUID return check3rdbyte(fname, S_ISUID #else return Qfalse; #endif }

size(file_name) → integer Show source

返回的file_name的大小。

file_name可以是IO对象。

static VALUE rb_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 }

size?(file_name) → Integer or nil Show source

返回nil如果file_name不存在或具有零大小,否则返回文件的大小。

file_name可以是IO对象。

static VALUE rb_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 }

socket?(file_name) → true or false Show source

如果指定的文件是套接字,则返回true

file_name可以是IO对象。

static VALUE rb_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; }

split(file_name) → array Show source

将给定的字符串拆分成一个目录和一个文件组件,并将它们返回到一个两元素数组中。另见File::dirnameFile::basename

File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]

static VALUE rb_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) }

stat(file_name) → stat Show source

返回File::Stat指定文件的对象(请参阅参考资料File::Stat)。

File.stat("testfile").mtime #=> Tue Apr 08 12:58:04 CDT 2003

static VALUE rb_file_s_stat(VALUE klass, VALUE fname) { struct stat st; FilePathValue(fname if (rb_stat(fname, &st) < 0) { rb_sys_fail_path(fname } return rb_stat_new(&st }

sticky?(file_name) → true or false Show source

返回true指定文件如果设置了粘滞位。

static VALUE rb_file_sticky_p(VALUE obj, VALUE fname) { #ifdef S_ISVTX return check3rdbyte(fname, S_ISVTX #else return Qnil; #endif }

symlink(old_name, new_name) → 0 Show source

为现有文件old_name创建一个名为new_name的符号链接。在不支持NotImplemented符号链接的平台上引发异常。

File.symlink("testfile", "link2test") #=> 0

static VALUE rb_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 }

symlink?(file_name) → true or false Show source

返回true指定文件是否为符号链接。

static VALUE rb_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(StringValueCStr(fname), &st) < 0) return Qfalse; if (S_ISLNK(st.st_mode)) return Qtrue; #endif return Qfalse; }

truncate(file_name, integer) → 0 Show source

截断文件FILE_NAME是在最整数字节长。不适用于所有平台。

f = File.new("out", "w") f.write("1234567890") #=> 10 f.close #=> nil File.truncate("out", 5) #=> 0 File.size("out") #=> 5

static VALUE rb_file_s_truncate(VALUE klass, VALUE path, VALUE len) { #ifdef HAVE_TRUNCATE #define NUM2POS(n) NUM2OFFT(n) off_t pos; #else #define NUM2POS(n) NUM2LONG(n) long pos; #endif pos = NUM2POS(len FilePathValue(path path = rb_str_encode_ospath(path #ifdef HAVE_TRUNCATE if (truncate(StringValueCStr(path), pos) < 0) rb_sys_fail_path(path #else /* defined(HAVE_CHSIZE) */ { int tmpfd; if ((tmpfd = rb_cloexec_open(StringValueCStr(path), 0, 0)) < 0) { rb_sys_fail_path(path } rb_update_max_fd(tmpfd if (chsize(tmpfd, pos) < 0) { int e = errno; close(tmpfd rb_syserr_fail_path(e, path } close(tmpfd } #endif return INT2FIX(0 #undef NUM2POS }

umask() → integer Show source

umask(integer) → integer

返回此过程的当前umask值。如果给出可选参数,请将umask设置为该值并返回以前的值。Umask值从默认权限中减去,所以umask 0222会为每个人创建一个只读文件。

File.umask(0006) #=> 18 File.umask #=> 6

static VALUE rb_file_s_umask(int argc, VALUE *argv) { int omask = 0; if (argc == 0) { omask = umask(0 umask(omask } else if (argc == 1) { omask = umask(NUM2INT(argv[0]) } else { rb_check_arity(argc, 0, 1 } return INT2FIX(omask }

unlink(file_name, ...) → integer Show source

删除指定的文件,返回作为参数传递的名称数量。发生任何错误都会引发异常。另见Dir::rmdir

static VALUE rb_file_s_unlink(int argc, VALUE *argv, VALUE klass) { return apply2files(unlink_internal, argc, argv, 0 }

utime(atime, mtime, file_name,...) → integer Show source

Sets the access and modification times of each named file to the first two arguments. Returns the number of file names in the argument list.

static VALUE rb_file_s_utime(int argc, VALUE *argv) { struct utime_args args; struct timespec tss[2], *tsp = NULL; apply2args(2 args.atime = *argv++; args.mtime = *argv++; if (!NIL_P(args.atime) || !NIL_P(args.mtime)) { tsp = tss; tsp[0] = rb_time_timespec(args.atime if (args.atime == args.mtime) tsp[1] = tsp[0]; else tsp[1] = rb_time_timespec(args.mtime } args.tsp = tsp; return apply2files(utime_internal, argc, argv, &args }

world_readable?(file_name) → integer or nil Show source

If file_name is readable by others, returns an integer representing the file permission bits of file_name. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

file_name can be an IO object.

File.world_readable?("/etc/passwd") #=> 420 m = File.world_readable?("/etc/passwd") sprintf("%o", m) #=> "644"

static VALUE rb_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; }

world_writable?(file_name) → integer or nil Show source

If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

file_name can be an IO object.

File.world_writable?("/tmp") #=> 511 m = File.world_writable?("/tmp") sprintf("%o", m) #=> "777"

static VALUE rb_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; }

writable?(file_name) → true or false Show source

Returns true if the named file is writable by the effective user and group id of this process. See eaccess(3).

static VALUE rb_file_writable_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (eaccess(StringValueCStr(fname), W_OK) < 0) return Qfalse; return Qtrue; }

writable_real?(file_name) → true or false Show source

Returns true if the named file is writable by the real user and group id of this process. See access(3)

static VALUE rb_file_writable_real_p(VALUE obj, VALUE fname) { FilePathValue(fname fname = rb_str_encode_ospath(fname if (access(StringValueCStr(fname), W_OK) < 0) return Qfalse; return Qtrue; }

zero?(file_name) → true or false Show source

Returns true if the named file exists and has a zero size.

file_name can be an IO object.

static VALUE rb_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; }

Public Instance Methods

atime → time Show source

Returns the last access time (a Time object)

for <i>file</i>, or epoch if <i>file</i> has not been accessed. File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969

static VALUE rb_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 }

birthtime → time Show source

Returns the birth time for file.

File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003

If the platform doesn't have birthtime, raises NotImplementedError.

static VALUE rb_file_birthtime(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_birthtime(&st }

chmod(mode_int) → 0 Show source

Changes permission bits on file to the bit pattern represented by mode_int. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. Follows symbolic links. Also see File#lchmod.

f = File.new("out", "w" f.chmod(0644) #=> 0

static VALUE rb_file_chmod(VALUE obj, VALUE vmode) { rb_io_t *fptr; int mode; #if !defined HAVE_FCHMOD || !HAVE_FCHMOD VALUE path; #endif mode = NUM2INT(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 }

chown(owner_int, group_int ) → 0 Show source

Changes the owner and group of file to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Follows symbolic links. See also File#lchown.

File.new("testfile").chown(502, 1000)

static VALUE rb_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 }

ctime → time Show source

Returns the change time for file (that is, the time directory information 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 VALUE rb_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 }

flock(locking_constant) → 0 or false Show source

Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.

Locking constants (in class File):

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 + 1 f.rewind f.write("#{value}\n") f.flush f.truncate(f.pos) } # read the counter using read lock File.open("counter", "r") {|f| f.flock(File::LOCK_SH) p f.read }

static VALUE rb_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 }

lstat → stat Show source

Same as IO#stat, but does not follow the last symbolic link. Instead, reports on the link itself.

File.symlink("testfile", "link2test") #=> 0 File.stat("testfile").size #=> 66 f = File.new("link2test") f.lstat.size #=> 8 f.stat.size #=> 66

static VALUE rb_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(RSTRING_PTR(path), &st) == -1) { rb_sys_fail_path(fptr->pathv } return rb_stat_new(&st #else return rb_io_stat(obj #endif }

mtime → time Show source

Returns the modification time for file.

File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003

static VALUE rb_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 }

path → filename Show source

to_path → filename

Returns the pathname used to create file as a string. Does not normalize the name.

File.new("testfile").path #=> "testfile" File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"

static VALUE rb_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)) return Qnil; return rb_obj_taint(rb_str_dup(fptr->pathv) }

size → integer Show source

Returns the size of file in bytes.

File.new("testfile").size #=> 66

static VALUE rb_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 }

to_path → filename Show source

Returns the pathname used to create file as a string. Does not normalize the name.

File.new("testfile").path #=> "testfile" File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"

static VALUE rb_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)) return Qnil; return rb_obj_taint(rb_str_dup(fptr->pathv) }

truncate(integer) → 0 Show source

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

f = File.new("out", "w") f.syswrite("1234567890") #=> 10 f.truncate(5) #=> 0 f.close() #=> nil File.size("out") #=> 5

static VALUE rb_file_truncate(VALUE obj, VALUE len) { rb_io_t *fptr; #if defined(HAVE_FTRUNCATE) #define NUM2POS(n) NUM2OFFT(n) off_t pos; #else #define NUM2POS(n) NUM2LONG(n) long pos; #endif 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 #ifdef HAVE_FTRUNCATE if (ftruncate(fptr->fd, pos) < 0) rb_sys_fail_path(fptr->pathv #else /* defined(HAVE_CHSIZE) */ if (chsize(fptr->fd, pos) < 0) rb_sys_fail_path(fptr->pathv #endif return INT2FIX(0 #undef NUM2POS }

Ruby Core © 1993–2017 Yukihiro Matsumoto

Licensed under the Ruby License.

Ruby Standard Library © contributors

Licensed under their own licenses.