如何将文件内容复制到另一个文件?

Mar*_*ark 4 ruby file-io

这看起来很基本,我根本无法将一个文件的内容复制到另一个文件.这是我到目前为止的代码:

#!/usr/bin/ruby

Dir.chdir( "/mnt/Shared/minecraft-server/plugins/Permissions" )

flist = Dir.glob( "*" )

flist.each do |mod|
    mainperms = File::open( "AwesomeVille.yml" )
    if mod == "AwesomeVille.yml"
        puts "Shifting to next item..."
        shift
    else
        File::open( mod, "w" ) do |newperms|
            newperms << mainperms
        end
    end
    puts "Updated #{ mod } with the contents of #{ mainperms }."
end
Run Code Online (Sandbox Code Playgroud)

the*_*Man 7

为什么要将一个文件的内容复制到另一个?为什么不使用操作系统来复制文件,或使用Ruby的内置FileUtils.copy_file

ri FileUtils.copy_file
FileUtils.copy_file

(from ruby core)
------------------------------------------------------------------------------
  copy_file(src, dest, preserve = false, dereference = true)

------------------------------------------------------------------------------

Copies file contents of src to dest. Both of src and
dest must be a path name.
Run Code Online (Sandbox Code Playgroud)

更灵活/更强大的替代方案是使用Ruby的内置FileUtils.cp:

ri FileUtils.cp
FileUtils.cp

(from ruby core)
------------------------------------------------------------------------------
  cp(src, dest, options = {})

------------------------------------------------------------------------------

Options: preserve noop verbose

Copies a file content src to dest.  If dest is a
directory, copies src to dest/src.

If src is a list of files, then dest must be a directory.

  FileUtils.cp 'eval.c', 'eval.c.org'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
  FileUtils.cp 'symlink', 'dest'   # copy content, "dest" is not a symlink
Run Code Online (Sandbox Code Playgroud)


小智 0

我意识到这不是完全认可的方式,但是

 IO.readlines(filename).join('') # join with an empty string because readlines includes its own newlines
Run Code Online (Sandbox Code Playgroud)

将文件加载到字符串中,然后您可以将其输出到 newperms 中,就像它是字符串一样。当前不起作用的原因很可能是您正在尝试将 IO 处理程序写入文件,而 IO 处理程序没有按照您希望的方式转换为字符串。

然而,另一个修复可能是

 newperms << mainperms.read
Run Code Online (Sandbox Code Playgroud)

另外,请确保在脚本退出之前关闭 mainperms,因为如果不这样做,可能会破坏某些内容。

希望这可以帮助。