Ruby - Create a Tar Archive

1. Introduction

While working with multiple files and directories, it's often helpful to combine them into a single file for easier management, backup, or sharing. The Tar (Tape Archive) format provides a straightforward way to achieve this. In this guide, we will explore how to create a Tar archive using Ruby.

Tar (Tape Archive) is a computer file format that can combine multiple files into a single file called a tarball. It's primarily used for collecting many files into one larger file for distribution or archiving without compression.

2. Program Steps

1. Import the necessary libraries.

2. Specify the files or directories to be included in the tar archive.

3. Create the tar archive and add the specified files or directories.

4. Close the tar archive after adding all desired content.

3. Code Program

# Import the necessary libraries
require 'rubygems/package'
require 'fileutils'
# List of files and directories to be archived
items_to_archive = ['file1.txt', 'file2.txt', 'directory1']
# Create the tar archive
File.open('archive.tar', 'wb') do |tar_file|
  Zlib::GzipWriter.wrap(tar_file) do |gzip_file|
    Gem::Package::TarWriter.new(gzip_file) do |tar|
      items_to_archive.each do |item|
        if File.directory?(item)
          # Add directories to the tar
          tar.mkdir(item, File.stat(item).mode)
        else
          # Add files to the tar
          tar.add_file_simple(item, File.stat(item).mode, File.size(item)) do |tar_file|
            tar_file.write(File.read(item))
          end
        end
      end
    end
  end
end
puts "Tar archive 'archive.tar' has been created."

Output:

Tar archive 'archive.tar' has been created.

Explanation:

1. require 'rubygems/package' and require 'fileutils': These lines import the necessary libraries to work with tar archives and files.

2. items_to_archive = ['file1.txt', 'file2.txt', 'directory1']: This line specifies the files or directories to be included in the tar archive.

3. File.open('archive.tar', 'wb') do |tar_file|: This line opens a new file in binary write mode to create the tar archive.

4. Zlib::GzipWriter.wrap(tar_file): Although tar itself doesn't compress the files, this line wraps the tar archive in a gzip writer for optional compression.

5. Gem::Package::TarWriter.new(gzip_file): This initializes the tar writer.

6. Inside the loop, we check if the item is a directory or a file with File.directory?(item). For directories, we add them to the tar using tar.mkdir. For files, we add them using tar.add_file_simple.