Objective
Create a program which behaves like the Unix command "more": it must display the contents of a text file, and ask the user to press Enter each time the screen is full.
As a simple approach, you can display the lines truncated to 79 characters, and stop after each 24 lines
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for file handling
using System;
using System.IO;
public class More
{
// Method to display the contents of a text file with pagination
public static void DisplayFile(string fileName)
{
// Using StreamReader to read the file line by line
using (StreamReader reader = new StreamReader(fileName))
{
int lineCount = 0; // Counter to keep track of lines displayed in a "page"
// Loop through each line in the file
while (!reader.EndOfStream)
{
// Reading a line from the file and truncating it to 79 characters if needed
string line = reader.ReadLine();
if (line.Length > 79)
line = line.Substring(0, 79);
// Displaying the line on the screen
Console.WriteLine(line);
lineCount++; // Incrementing the line counter
// Checking if 24 lines have been displayed
if (lineCount == 24)
{
// Pausing and waiting for the user to press Enter to continue
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
lineCount = 0; // Resetting the line counter for the next page
}
}
}
}
}
// Auxiliary class to test the More functionality
public class Program
{
public static void Main()
{
// Prompting the user to enter the name of the file to display
Console.Write("Enter the file name to display: ");
string fileName = Console.ReadLine();
// Checking if the file exists before attempting to display
if (File.Exists(fileName))
{
// Displaying the contents of the file with pagination
More.DisplayFile(fileName);
}
else
{
// Displaying an error message if the file does not exist
Console.WriteLine("The file does not exist.");
}
}
}