Group
File Handling in C#
Objective
1. Provide a C# source code file as input.
2. The program parses the C# code and identifies basic constructs like loops, conditionals, and method definitions.
3. It converts the identified constructs into Pascal syntax.
4. The translated Pascal code is saved to a new output file.
Example usage:
convertToPascal inputFile.cs outputFile.pas
Create a program that converts simple C# programs, such as the following one, to the Pascal language.
Example C# Exercise
Show C# Code
using System;
using System.IO;
class CSharpToPascalConverter
{
// Main method where the program starts execution
static void Main(string[] args)
{
// Check if the user provided the input and output filenames as command line arguments
if (args.Length != 2)
{
Console.WriteLine("Usage: convertToPascal ");
return;
}
// Get the input and output file paths from the command line arguments
string inputFile = args[0];
string outputFile = args[1];
try
{
// Open the input C# file for reading
string csharpCode = File.ReadAllText(inputFile);
// Convert C# code to Pascal syntax
string pascalCode = ConvertCSharpToPascal(csharpCode);
// Write the Pascal code to the output file
File.WriteAllText(outputFile, pascalCode);
Console.WriteLine("C# code has been converted to Pascal and saved to " + outputFile);
}
catch (Exception ex)
{
// If there was an error, display the error message
Console.WriteLine($"Error: {ex.Message}");
}
}
// Method to convert C# code to Pascal code
static string ConvertCSharpToPascal(string csharpCode)
{
// Convert common C# constructs to Pascal syntax
csharpCode = csharpCode.Replace("public class", "program");
csharpCode = csharpCode.Replace("static void Main", "begin");
csharpCode = csharpCode.Replace("Console.WriteLine", "writeln");
csharpCode = csharpCode.Replace("Console.ReadLine", "readln");
csharpCode = csharpCode.Replace("{", "begin");
csharpCode = csharpCode.Replace("}", "end.");
csharpCode = csharpCode.Replace("int", "integer");
csharpCode = csharpCode.Replace("string", "string");
// Convert for loops
csharpCode = csharpCode.Replace("for (int i =", "for i :=");
csharpCode = csharpCode.Replace("i < ", "i <= ");
csharpCode = csharpCode.Replace("i++)", "do");
csharpCode = csharpCode.Replace("}", "end");
// Convert if statements
csharpCode = csharpCode.Replace("if (", "if ");
csharpCode = csharpCode.Replace("else", "else");
// Return the converted Pascal code
return csharpCode;
}
}
Output
//Case 1 - Successful Conversion:
//For the command:
convertToPascal inputFile.cs outputFile.pas
//Output:
C# code has been converted to Pascal and saved to outputFile.pas
//Case 2 - Error (File Not Found):
//For the command:
convertToPascal nonExistentFile.cs outputFile.pas
//Output:
Error: The system cannot find the file specified.