Exercise
Invert A Text File
Objective
Create a program to "invert" the contents of a text file: create a file with the same name ending in ".tnv" and containing the same lines as the original file but in reverse order (the first line will be the last one, the second will be the penultimate, and so on, until the last line of the original file, which should appear in the first position of the resulting file).
Hint: the easiest way, using only the programming structures we know so far, is reading the source files two times: the first time to count the amount of lines in the file, and the second time to store them in an array.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System; // Importing the System namespace for basic C# functionality
using System.IO; // Importing the IO namespace for file operations
public class InvertFileContents
{
// Method to invert the contents of the text file
public static void InvertFile(string inputFile)
{
// Generate the output file name by appending ".tnv" to the input file name
string outputFile = Path.ChangeExtension(inputFile, ".tnv");
// Read all lines from the input file
string[] lines = File.ReadAllLines(inputFile); // Read all lines into an array
// Open the output file for writing
using (StreamWriter writer = new StreamWriter(outputFile)) // Open the output file in write mode
{
// Write the lines in reverse order
for (int i = lines.Length - 1; i >= 0; i--) // Loop through the array in reverse order
{
writer.WriteLine(lines[i]); // Write the current line to the output file
}
}
// Notify the user that the file inversion is complete
Console.WriteLine($"File '{inputFile}' has been inverted and saved as '{outputFile}'."); // Print success message
}
}
class Program
{
// Main method where the program execution starts
static void Main(string[] args)
{
// Check if the user provided the file name as an argument
if (args.Length < 1) // If no file name is provided
{
Console.WriteLine("Please provide the input text file."); // Prompt user to provide the file
return; // Exit the program if no file is provided
}
string inputFile = args[0]; // Assign the input file name from the command line argument
// Check if the input file exists
if (!File.Exists(inputFile)) // If the input file doesn't exist
{
Console.WriteLine($"The file '{inputFile}' does not exist."); // Print error message
return; // Exit the program if the file doesn't exist
}
// Call the method to invert the contents of the file
InvertFileContents.InvertFile(inputFile); // Invert the file contents and save the result
}
}