Question

Description: Merge two or more text files provided by the user into a new text file...

Description: Merge two or more text files provided by the user into a new text file where the names of the text files to join and the output text file are provided to the program using command line arguments.

Purpose: This application provides experience working with command line arguments, writing files to disk, reading files from disk, working with exceptions, and writing programs in C#/.NET.

Requirements:

Project Name: DocumentMerger2
Target Platform: Console
Programming Language: C#

In a previous challenge, Document Merger (Links to an external site.), you wrote a program to merge text documents provided by the user into a new text file where you prompted the user in the consolefor the names of the text files to merge as well as the resulting merged text file.

In this challenge, the functionality of being able to merge text documents is to be the same as Document Merger. The difference in this challenge is that the names of the text files to join and the output text file are provided to the program using command line arguments. Instead of prompting the user for the names (paths to the files), that information is provided via command line arguments.

The command line arguments are provided to the Main() function in C#:

class Program {
     static void Main(string[] args) {
          // args is a string[] of command line arguments
     
     }
}

The length of the array can be determined using the Length property of the array.

args.Length

If two text files are to be merged, three command line arguments are supplied to the program. The first two command line arguments are the the names of the text files to merge and the third command line argument is the name of the resulting merged text file. In this case the args array of strings is to contain three strings.

If three text files are to be merged, four command line arguments are supplied to the program. The first three command line arguments are the the names of the text files to merge and the fourth command line argument is the name of the resulting merged text file. In this case the args array of strings is to contain four strings.

Support for merging two or more files is to be supported in the application. The number of command line arguments minus one is the number of text files to merge. If six text files are to be merged, seven command line arguments are supplied with the seventh being the name of the resulting merged text file.

If two command line arguments or less are supplied, then a merger of text documents is not possible. In this case the user is to be presented with information on how to use the program and the program is to exit (quit).

if (args.Length < 3) {
     Console.WriteLine("DocumentMerger2 <input_file_1> <input_file_2> ... <input_file_n> <output_file>")
     Console.WriteLine("Supply a list of text files to merge followed by the name of the resulting merged text file as command line arguments.")
}

How command line arguments are supplied to a C#/.NET/Console application depends on the platform and how the program is run. Be sure to check out the following documents that cover how to write and run a program that accepts command line arguments and how to provide command line arguments to an application in different contexts (in Visual Studio/on the command line/mac OS/Windows).

  • Building and Running Console App (Links to an external site.)

  • Command Line Parameters Inside Visual Studio (Links to an external site.)

If any exceptions occur during the execution of the program, they are to be handled and the user is to be presented with informative error messages. The program is not to crash when an exception occurs. An exception might occur if a provided filename doesn’t exist or there is an error writing the output file.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • Create a file named "MergeFiles.cs" and insert the following code into it:

using System;
using System.IO;
namespace Merging
{   
class MergeFiles{   
  
// Main Method which accepts the command line arguments as string type parameters   
static void Main(string[] args)
{   
  
// If length of Command line arguments < 3 then merger of text documents is not possible
if(args.Length < 3)
{
Console.WriteLine("DocumentMerger2 <input_file_1> <input_file_2> ... <input_file_n> <output_file>");
Console.WriteLine("Supply a list of text files to merge followed by the name of the resulting merged text file as command line arguments.");
System.Environment.Exit(1); // stop the execution of program
}
else
{
StreamWriter sw = null;
try
{
// This will create a new file (merged file) with the specified name at the specified location for writing operations
sw = new StreamWriter(args[args.Length - 1] + ".txt");
}
catch (FileNotFoundException) {
Console.WriteLine("The " + args[args.Length - 1] + ".txt file cannot be found.");
}
catch (DirectoryNotFoundException) {
Console.WriteLine("The directory cannot be found.");
}
catch (DriveNotFoundException) {
Console.WriteLine("The drive specified in merged file's path is invalid.");
}
catch (PathTooLongException) {
Console.WriteLine("The merged file's path exceeds the maxium supported path length.");
}
catch (UnauthorizedAccessException) {
Console.WriteLine("You do not have permission to create " + args[args.Length - 1] + ".txt file.");
}
catch (IOException) {
Console.WriteLine("An IO exception occurred while creating " + args[args.Length - 1] + ".txt file.");
}
  
// One by one, open the text files that are to be merged, read their contents line by line and simultaneously write them into the merged file opened earlier
for(int i=0; i<args.Length-1; ++i)
{
       StreamReader sr = null;
       try
       {
       //Opening a specified text file for reading operations
       sr = new StreamReader(args[i] + ".txt");
      
       // This is use to specify to start reading the opened text file from the beginning
       sr.BaseStream.Seek(0, SeekOrigin.Begin);
       }
       catch (FileNotFoundException) {
Console.WriteLine("The " + args[i] + ".txt file cannot be found.");
}
catch (DirectoryNotFoundException) {
Console.WriteLine("The directory cannot be found.");
}
catch (DriveNotFoundException) {
Console.WriteLine("The drive specified in merged file's path is invalid.");
}
catch (PathTooLongException) {
Console.WriteLine("The merged file's path exceeds the maxium supported path length.");
}
catch (UnauthorizedAccessException) {
Console.WriteLine("You do not have permission to read " + args[i] + ".txt file.");
}
catch (IOException) {
Console.WriteLine("An IO exception occurred while opening " + args[i] + ".txt file.");
}
  

// To read a line from the file
string str = sr.ReadLine();
  
// To read the whole file line by line and simultaneously write it to the merged file
while (str != null)
{
sw.WriteLine(str);
           str = sr.ReadLine();
}
  
// to close the read stream
       sr.Close();
}
sw.Flush();
// to close the write stream
sw.Close();
}   
}
}
}

Please refer to the below screenshots to understand the indentation of the code:

Add a comment
Know the answer?
Add Answer to:
Description: Merge two or more text files provided by the user into a new text file...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed...

    Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed as command-line arguments to MergeFiles as follows: java MergeFiles filel file2 mergedFile II. MergeFiles reads names stored in files file and file2 III. Merges the two list of names into a single list IV. Sorts that single list V. Ignores repetitions VI. Writes the sorted, free-of-repetitions list to a new file named mergedFile.txt VII. The names in all three files are stored as one...

  • Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text...

    Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text file by removing all blank lines (including lines that only contain white spaces), all spaces/tabs before the beginning of the line, and all spaces/tabs at the end of the line. The file must be saved under a different name with all the lines numbered and a single blank line added at the end of the file. For example, if the input file is given...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Create a program called Merge.java that implements a variety of the Merge function (in the Merge...

    Create a program called Merge.java that implements a variety of the Merge function (in the Merge Sort algorithm). The program should be able to do the following: accepts two command line parameters, each specifies a text file containing the integers to be merged. The structure of the files is as follows: For both files, there will be multiple lines, each of which contains one integer. The number of lines is unknown. reads the integers from the text files into two...

  • //Done in C please! //Any help appreciated! Write two programs to write and read from file...

    //Done in C please! //Any help appreciated! Write two programs to write and read from file the age and first and last names of people. The programs should work as follows: 1. The first program reads strings containing first and last names and saves them in a text file (this should be done with the fprintf function). The program should take the name of the file as a command line argument. The loop ends when the user enters 0, the...

  • C++ Write a program with the following elements: in main() -opens the 2 files provided for...

    C++ Write a program with the following elements: in main() -opens the 2 files provided for input (Lab_HW9_2Merge1.txt and Lab_HW9_2Merge2.txt) -calls a global function to determine how many lines are in each file -creates 2 arrays of the proper size -calls a global function to read the file and populate the array (call this function twice, once for each file/array) -calls a global function to write out the 'merged' results of the 2 arrays *if there are multiple entries for...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • Write a python program that prompts the user for the names of two text files and...

    Write a python program that prompts the user for the names of two text files and compare the contents of the two files to see if they are the same. If they are, the scripts should simply output “Yes”. If they are not, the program should output “No”, followed by the first lines of each file that differ from each other. The input loop should read and compare lines from each file. The loop should break as soon as a...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

  • Merge the following two text files to another text file named "allstudents.txt". The new file should...

    Merge the following two text files to another text file named "allstudents.txt". The new file should be sorted in terms of the students' graduation date from the nearest to furthest. (USING JAVA PROGRAMMING LANGUAGE) Text file: boys.txt NAME,ID,GRADUATION_DATE,AGE 1. John, 6, 2020-07-01 10:50:00 EST, 22 2. Mike, 9, 2020-07-07 10:40:00 EST, 23 3. Lucas, 10, 2020-07-07 10:42:00 EST, 23 Text file: girls.txt NAME,ID,GRADUATION_DATE,AGE 1. Emma, 7, 2020-06-02 10:50:00 EST, 22 2. Olivia, 4, 2020-07-06 10:40:00 EST, 21 3. Sophia, 1,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT