Grupo
Manejo de archivos en C#
Objectivo
1. Proporcione un archivo de código fuente de C# como entrada.
2. El programa analiza el código de C# e identifica construcciones básicas como bucles, condicionales y definiciones de métodos.
3. Convierte las construcciones identificadas a sintaxis Pascal.
4. El código Pascal traducido se guarda en un nuevo archivo de salida.
Ejemplo de uso:
convertToPascal inputFile.cs outputFile.pas
Cree un programa que convierta programas sencillos de C#, como el siguiente, a Pascal.
Ejemplo de ejercicio en C#
Mostrar código C#
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.
Código de ejemplo copiado
Comparte este ejercicio de C#