A. User
A. User

Reputation: 33

Create a file in every subdirectory

I want to iterate through every subdirectory inside a directory (no need to iterate deeper than that) and create a file within each.

For example:

C:\
-C:\folder1
-C:\folder2
-...

I want to end up with a file in each of these folders:

C:\
-C:\folder1\file1.txt
-C:\folder2\file2.txt
-...

The code I've tried is

require 'securerandom'

array =[]

IO.foreach('output.txt') { |line|
  array<<line
}

array.each { |folder|
  randomName = SecureRandom.hex
  File.open("#{folder}\\#{randomName}.txt", 'wb+') do |f|
      buffer = ((SecureRandom.hex)*8).freeze
      randomNumber = (rand 1..9)
      randomNumber.kilobytes.times { f.write buffer }
  end
}

Where output.txt is a file with the full directory of all my desired folders, separated by newlines, e.g.:

output.txt:

"C:\Users\folder1"
"C:\Users\folder2"
...

As for SecureRandom.hex, I just need the contents and file sizes of the files to be random.

Thank you again for your kind help!

Upvotes: 2

Views: 85

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

You can use this as template:

i = 0
Dir['c:\*'].each do | subdir |
  next unless File.directory?(subdir)
  File.open("#{subdir}/file#{i}.txt", "w") { | io | io << 'foo' }
  i += 1
end

Upvotes: 1

Related Questions