Creating an Empty File in Ruby: "Touch" Equivalent

Creating an empty file in Ruby: touch equivalent?

FileUtils.touch looks like what it does, and mirrors* the touch command:

require 'fileutils'
FileUtils.touch('file.txt')

* Unlike touch(1) you can't update mtime or atime alone. It's also missing a few other nice options.

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

How do I create directory if none exists using File class in Ruby?

You can use FileUtils to recursively create parent directories, if they are not already present:

require 'fileutils'

dirname = File.dirname(some_path)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end

Edit: Here is a solution using the core libraries only (reimplementing the wheel, not recommended)

dirname = File.dirname(some_path)
tokens = dirname.split(/[\/\\]/) # don't forget the backslash for Windows! And to escape both "\" and "/"

1.upto(tokens.size) do |n|
dir = tokens[0...n]
Dir.mkdir(dir) unless Dir.exist?(dir)
end

Open directory and create new file

You just need to do

path_name = "#{project_name}/new_folder"
FileUtils::mkdir_p path_name
FileUtils::touch("#{path_name}/README.md")

This will create an empty file named README.md inside your project_name/new_folder directory.

How to create the empty 'Icon\r' file for a .dmg from shell script?

echo -e "Icon\\r" | xargs touch


Related Topics



Leave a reply



Submit